首页 > 解决方案 > 无法将数据上传到 Firebase 数据库?

问题描述

我正在按照说明测试 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);
        }

标签: androidfirebasefirebase-realtime-database

解决方案


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


推荐阅读