简体   繁体   中英

Reading data from a firebase database snapshot

So, I'm trying to take a snapshot of my Database and add the items with its child's in array-strings.

我的数据库看起来像这样

My main activity looks like this

    private Button mbutton;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advanced_search);
        mbutton = findViewById(R.id.button_search);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        mbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goListener();
            }
        });
    }
    private void goListener() {
        myRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                dataQuery(snapshot);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
    private void dataQuery(DataSnapshot snapshot) {
        for (int y = 0; y !=2; y++) {
            for (DataSnapshot ds : snapshot.getChildren()) {
                AdvancedQuery findInfo = new AdvancedQuery();
                findInfo.setName(ds.child(String.valueOf(y)).getValue(AdvancedQuery.class).getName());
                findInfo.setIngredients(ds.child(String.valueOf(y)).getValue(AdvancedQuery.class).getIngredients());
            }
        }
    }
}

And my set and get java file looks like this

public class AdvancedQuery {
    public String name, ingredients;
    public AdvancedQuery(){ }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIngredients() {
        return ingredients;
    }
    public void setIngredients(String ingredients) {
        this.ingredients = ingredients;
    }
}

However, when my program gets to the dataQuery method and tries get and set the name and ingredients, it crashes. Can someone explain what I've done wrong and if there are any better ways to do this with database snapshot?

Process: in.tvac.akshayejh.firebasesearch, PID: 24798 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String in.tvac.akshayejh.firebasesearch.AdvancedQuery.getName()' on a null object reference at in.tvac.akshayejh.firebasesearch.AdvancedSearch.dataQuery(AdvancedSearch.java:140) at in.tvac.akshayejh.firebasesearch.AdvancedSearch.access$500(AdvancedSearch.java:20) at in.tvac.akshayejh.firebasesearch.AdvancedSearch$2.onDataChange(AdvancedSearch.java:115) at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.4:183) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63) at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handl er.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

As far as I can see you're not initializing myRef anywhere, which would lead to a NullPointerException when you do myRef.addListenerForSingleValueEvent(... .

If that is indeed the error you get, make sure to initialize myRef before using it, with something like:

myRef = FirebaseDatabase.getInstance().getReference().child("Recipes");

I'm not entirely sure if the .child("Recipes") is needed, so remove/modify to fit your data model and the logic of your code.

It's really hard to parse what your `` is doing. The idiomatic approach is to read only the Recipes node, and then loop over the child nodes under there with snapshot.getChildren() .

So something like:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Recipes");

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot recipeSnapshot: snapshot.getChildren()) {
            AdvancedQuery findInfo = recipeSnapshot.getValue(AdvancedQuery.class);

            ...

        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // NEVER ignore errors
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM