Wildan Romiza
Wildan Romiza

Reputation: 43

Retrieved data from firebase always null

I have data. I want to get data from Firebase. This is my structure:

"data" : {
   "A01" : {
     "status" : 1,
     "tglkeluar" : "12-03-2019"
    },
   "A02" : {
     "status" : 1,
     "tglkeluar" : "10-03-2019"
   }
 },

This is my structure:

structure

And I used this code to get data from child "A01" only:

mDatabaseA01 = FirebaseDatabase.getInstance().getReference("data").child("A01");
mDatabaseA01.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
            Data status = postSnapshot.getValue(Data.class);
            Toast.makeText(HalamanAdmin.this, status.getStatus(), Toast.LENGTH_SHORT).show();
        }
    }

But the data is null. What am I doing wrong now?

Upvotes: 2

Views: 61

Answers (1)

Lucem
Lucem

Reputation: 3082

Here is the problem

for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
    Data status = postSnapshot.getValue(Data.class);
    Toast.makeText(HalamanAdmin.this, status.getStatus(), Toast.LENGTH_SHORT).show();
 }

Your data no longer exists with children objects since you are inside the children. Instead, you should do this

Data status = new Data(dataSnapshot.get("status"), dataSnapshot.get("tglkeluar");

Please remember to have the constructor on the Data class

public Data(String status, String tglkeluar){
    this.status = status;
    this.tglkeluar = tglkeluar;
}

Upvotes: 2

Related Questions