Fedya Nosplay
Fedya Nosplay

Reputation: 5

Getting Information from Firebase Database

I am trying to retrieve data from firebase realtime database. I have this structure:

firebase structure

Now I tried to query it like this:

private void firebaseListView(){

    Query query = FirebaseDatabase.getInstance().getReference()
            .child("expenses")
            .child(mAuth.getCurrentUser().getUid())
            .orderByValue();

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                Expenses expenses = dataSnapshot.getValue(Expenses.class);

                mExpenseList.add(expenses);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

mExpenseList is an array of the class Expenses It looks like this:

private long id;
private String name;
private double value;
private String category;
private String date;
private String location;
private long category_id;
private String firebase_id;

When I run the debugger I get the information from the database, but it says:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

How can I fix this?

Upvotes: 0

Views: 39

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

You are getting this error because you are trying to add objects of type Expenses class to a list that has never been initialized. To solve this, just create your mExpenseList variable, as a global variable:

private List<Expenses> mExpenseList;

And then in your onCreate() method initialize it using the following line of code:

mExpenseList = new ArrayList<>();

That's it!

Upvotes: 1

Related Questions