android - 从android中的firebase数据库中检索 child

标签 android firebase firebase-realtime-database

我正在尝试从我的 firebase 中检索 2 个数据分支,但我得到了一个 nullpointException,我不知道为什么

这是数据库

enter image description here

获取 cooking 时间和类别的代码

 FirebaseDatabase.getInstance().getReference().child( "recipes" )
                .addListenerForSingleValueEvent( new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            /*Recipe recipe = snapshot.getValue( Recipe.class );*/

                            DatabaseReference recipes = FirebaseDatabase.getInstance().getReference("recipes");
                            Recipe recipe_test = snapshot.child( "recipe_1" ).getValue(Recipe.class);



                            category.setText( recipe_test.getCategory() );
                            cookinTime.setText( recipe_test.getCookingtime() );


                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                } );
    }

配方类

package com.example.myapplicationdatatest;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

public class Recipe {

    private String category;
    private long cookingtime;
    private String description;
    private Map<String, Object> amountOfIngredients;
    private String nameOfRecipe;
    private Map<String, Object> Ingredients;

    public Recipe() {};



       public Recipe(String category, long cookingtime, String description,Map<String, Object> amountOfIngredients, String nameOfRecipe, Map<String, Object> Ingridients) {
            this.category=category;
            this.cookingtime=cookingtime;
            this.description=description;
            this.amountOfIngredients=amountOfIngredients;
            this.nameOfRecipe=nameOfRecipe;
            this.Ingredients=Ingridients;
        }

        public String getCategory() {
            return category;
        }

        public String getCookingtime() {
            long ct = cookingtime;
            String result = String.valueOf( ct );
            return result;
        }

        public String getDescription() {
            return description;
        }

        public Map<String, Object> getAmountOfIngredients() {
            return amountOfIngredients;
        }

        public String getNameOfRecipe() {
            return nameOfRecipe;
        }

        public Map<String, Object> getIngredients() {
            return Ingredients;
        }




    }

和异常

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplicationdatatest, PID: 20846
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.myapplicationdatatest.Recipe.getCategory()' on a null object reference
        at com.example.myapplicationdatatest.MainActivity$1.onDataChange(MainActivity.java:73)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.1.0:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.1.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.1.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.1.0:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 20846 SIG: 9
Disconnected from the target VM, address: 'localhost:8611', transport: 'socket'

我为数据库创建了一个有效的食谱类,因为我之前在数据库中只有一个食谱时尝试过

谢谢你的帮助

最佳答案

使用.getValue()时,注意:

This method is used to marshall the data contained in this snapshot into a class of your choosing. The class must fit 2 simple constraints:

  1. The class must have a default constructor that takes no arguments
  2. The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized

我建议在定义类变量后,只需在 Android Studio 中执行 Alt+Insert 即可生成公共(public) getters-setters。

此外,正如弗兰克在他的回答中指出的那样,您将通过执行以下操作在“食谱”下收到所有食谱:

FirebaseDatabase.getInstance().getReference().child( "recipes" )
    .addListenerForSingleValueEvent( new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Recipe recipe_test = snapshot.getValue( Recipe.class );
            }
        });

现在在 for-each 循环中,您需要使用这些值。例如,当您想要具有 key = "recipe_2"的快照时,您需要这样做:

if( snapshot.getKey().equals("recipe_2")) {
    //do your stuff
}

完整代码:

FirebaseDatabase.getInstance().getReference().child( "recipes" )
    .addListenerForSingleValueEvent( new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if( snapshot.getKey().equals("recipe_2")) {
                     //do your stuff           
                     Recipe recipe_2 = snapshot.getValue( Recipe.class );
                }
            }
        });

关于android - 从android中的firebase数据库中检索 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925507/

相关文章:

java - 无法在 firebase 数据库中保存消息

typescript - 如何查询ISO日期为今天的对象?

java - 在可运行中获取 firebase 数据

java - 来自用户模型的 ArrayList 返回 null

java - 按下按钮时未输入任何内容时 Android 应用程序崩溃

android - "java.lang.SecurityException:Injecting to another application requires INJECT_EVENTS permission"多个 Activity 工作流测试 android 时出错

java - 为什么我的应用程序无法从 Firebase 捕获任何数据?

android - 弹出的 React Native 应用程序无法到达 Firestore 后端

Android 构建错误

ios - Auth.auth.currentUser.uid 即使登录有效也无法正常工作