【问题标题】:Can't upload data to firebase database?无法将数据上传到 Firebase 数据库?
【发布时间】:2018-06-11 17:41:30
【问题描述】:

我正在关注instruction 来测试firebase 实时数据库,但是在保存数据后(运行下面的initialize() 和saveData() 方法)在控制台上看不到任何数据。 并且日志没有显示任何错误。 有什么问题?

public static void initialize() {
        // Fetch the service account key JSON file contents
        try {
            FileInputStream serviceAccount = new FileInputStream(keyPath);
            // Initialize the app with a service account, granting admin privileges
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                    .setDatabaseUrl("https://myprojectId.firebaseio.com")
                    .build();
            FirebaseApp.initializeApp(options);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public static void saveData() {
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("test");

        DatabaseReference usersRef = ref.child("vocabularies");

        Map<String, Vocabulary> vocabularies = new HashMap<>();

        Vocabulary v1 = new Vocabulary();
        v1.setWord("hello");
        v1.setDefinition("hello definition");
        v1.setTranslation("hello translation");

        Vocabulary v2 = new Vocabulary();
        v2.setWord("world");
        v2.setDefinition("world definition");
        v2.setTranslation("world translation");

        vocabularies.put("hello", v1);
        vocabularies.put("world", v2);

        usersRef.setValueAsync(vocabularies);
        }

【问题讨论】:

  • 您展示的功能是 Admin SDK 的一部分,而不是 Android。我看到这是用 Android 标记的,所以如果您尝试在 Android 应用程序中使用它,Alex 是正确的,该功能不存在。如果您尝试使用此服务器端,Louise 是正确的,程序在工作完成之前退出,您需要包含一些功能以保持线程处于活动状态,直到工作完成。

标签: android firebase firebase-realtime-database


【解决方案1】:

根据关于DatabaseReference 类的官方文档,没有setValueAsync() 方法。唯一可以帮助您直接在引用上设置值的方法是 setValue() 方法。

【讨论】:

  • 一切都好吗?我可以帮助您了解其他信息吗?
【解决方案2】:

求助有经验的工程师,是因为保存数据任务是在一个新线程中运行,在主线程完成时数据上传之前就终止了。为了验证解释,我简单地添加了

Thread.sleep(3000);

在 main 方法中的 saveData() 之后。成功了。

【讨论】:

    【解决方案3】:

    在我的情况下,错误是因为我没有为 https://console.developers.google.com/apis/api/securetoken.googleapis.com/overview?project= 的项目启用令牌服务 API 在此处插入您的项目名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多