Reputation: 361
I am trying to fill my listview with data from firebase query. My code:
public class ShowGoalsListActivity extends AppCompatActivity {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference messages = mDatabase.child("messages");
ArrayList<String> NameList = new ArrayList<String>();;
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.goals_list);
ListView animalList=(ListView)findViewById(R.id.listViewAnimals);
getNames();
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, NameList);
animalList.setAdapter(arrayAdapter);
animalList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
{
String selectedAnimal=NameList.get(position);
Toast.makeText(getApplicationContext(), "Animal Selected : "+selectedAnimal, Toast.LENGTH_LONG).show();
}
});
}
void getNames()
{
Query queryRef = messages.orderByChild("pages");
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map data = (Map ) dataSnapshot.getValue();
String name = (String) data.get("name");
NameList.add(name);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot){
}
@Override
public void onCancelled(DatabaseError databaseError){}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s1){}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s2){}
});
}
}
But when I go to my layout this listview is empty. But if I then go to another layout and then came back to goals_list layout listview contains all elements that I need. What can be a problem?
Upvotes: 0
Views: 1123
Reputation: 598765
The data is loaded from Firebase asynchronously. To alert Android that it needs to redraw the list view, you have to call notifyDataSetChanged()
after you change the data of the adapter.
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map data = (Map ) dataSnapshot.getValue();
String name = (String) data.get("name");
NameList.add(name);
arrayAdapter.notifyDataSetChanged();
}
To make this work, you'll need to make arrayAdapter
into ` member field of the activity:
public class ShowGoalsListActivity extends AppCompatActivity {
ArrayAdapter<String> arrayAdapter;
...
Upvotes: 1