首页 > 解决方案 > 从android中的firebase数据库中检索孩子

问题描述

我试图从我的火力库中检索 2 个数据分支,但是我得到了一个 nullpointException,我不知道为什么

这是数据库

在此处输入图像描述

检索烹饪时间和类别的代码

 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'

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

谢谢你的帮助

标签: androidfirebasefirebase-realtime-database

解决方案


你正在听recipes,然后在它下面的孩子身上循环。这意味着在第一次迭代snapshot中将指向recipe_1已经,并且您不再需要为该孩子分配子地址:

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 );

如果您想明确获取某些食谱,请摆脱循环并使用直接child("...")访问:

FirebaseDatabase.getInstance().getReference().child( "recipes" )
    .addListenerForSingleValueEvent( new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Recipe recipe1 = dataSnapshot.child("recipe_1").getValue( Recipe.class );
            Recipe recipe2 = dataSnapshot.child("recipe_2").getValue( Recipe.class );

推荐阅读