Reputation: 189
I am a beginner in Firebase. To create a leaderboard-like list in my android app, I have set up a database on firebase, as shown below:
Where all the userUIDs are under the "users" node, and under each userUID node are the user's data. I was trying to use the Query class methods to access 3 users having the top-3 highest "totalIMPs" value, and show their "name" on a Listview (list_TotalIMPs). To do this, I tried the following codes:
final ArrayAdapter<String> adapter_totalIMPs=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1);
list_TotalIMPs=(ListView)findViewById(R.id.listView_TotalIMPs);
list_TotalIMPs.setAdapter(adapter_totalIMPs);
Query query1=databaseReference.child("users").orderByChild("totalIMPs").limitToLast(3);
query1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
adapter_totalIMPs.clear();
adapter_totalIMPs.add("1");//for testing
adapter_totalIMPs.add("2");//for testing
adapter_totalIMPs.add("3");//for testing
for(DataSnapshot postsnapshot:dataSnapshot.getChildren())
{
adapter_totalIMPs.add((String)postsnapshot.child("name").getValue());
Toast.makeText(MainActivity.this,"Add in list: "+(String)postsnapshot.child("name").getValue(),Toast.LENGTH_LONG).show();
}
}
@Override public void onCancelled(DatabaseError databaseError){Toast.makeText(MainActivity.this,"Add in list: CANCELLED",Toast.LENGTH_LONG).show();}
});
However, only the testing Strings "1", "2", and "3" appeared on my list, and also, there is no Toast showing. This means that a problem occuured in the "for" loop, and I guess it has something to do with the database structure. But I am having a problem figuring this out. Can someone help? Thank you so much.
(I was wondering if the datasnapshot is empty so that the "for" loop was never entered?)
Upvotes: 0
Views: 167
Reputation: 11344
You are setting the adapter beforing reading the data. Try setting your adapter in your onChange method:
Query query1=databaseReference.child("users").orderByChild("totalIMPs").limitToLast(3);
query1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
adapter_totalIMPs.clear();
adapter_totalIMPs.add("1");//for testing
adapter_totalIMPs.add("2");//for testing
adapter_totalIMPs.add("3");//for testing
for(DataSnapshot postsnapshot:dataSnapshot.getChildren())
{
adapter_totalIMPs.add((String)postsnapshot.child("name").getValue());
Toast.makeText(MainActivity.this,"Add in list: "+(String)postsnapshot.child("name").getValue(),Toast.LENGTH_LONG).show();
}
list_TotalIMPs.setAdapter(adapter_totalIMPs);
}
@Override public void onCancelled(DatabaseError databaseError){Toast.makeText(MainActivity.this,"Add in list: CANCELLED",Toast.LENGTH_LONG).show();}
});
Upvotes: 1