Why is my ListView not updating after adding new data to Firebase?
I'm having trouble rebooting ListView
after pushing a line on firebase. ListView
updates when the application is restarted. I have used the function notifyDataSetChanged()
with mine ListAdapter
. That's what I'm doing:
myFirebaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("App",dataSnapshot.getValue().toString());
names = dataSnapshot.getValue().toString();
String[] planets = new String[] { names, "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune"};
ArrayList<String> planetList = new ArrayList<String>();
namesList.addAll( Arrays.asList(planets) );
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, android.R.id.text1, namesList);
mainListView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
+3
source to share
2 answers
Fire Engineer is here,
I would recommend checking out a simple chat example I did recently (what you are trying to do in detail here ), or our fuller context Android Chat example , which both demonstrate how to use model objects to bind to ArrayAdapters and ListViews.
TL; DR is what you want to do something more:
// Create instance variables to be used from inside your activity
private ArrayList<Map<String, Object>> mMessages;
private Firebase mRef;
...
// Some time later, instantiate your instance variables
this.mMessages = new ArrayList<Message>();
// Set up ListAdapter
ListAdapter messageAdapter = new ArrayAdapter(this , R.layout.message_layout , mMessages);
this.setListAdapter(messageAdapter);
// Set up Firebase
Firebase.setAndroidContext(this);
this.mRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
// Add listener to your Firebase database reference
this.mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Create objects and add to ArrayList, which should fire ArrayAdapter methods and update the ListView
Map<String, Object> data = (Map<String, Object>)dataSnapshot.getValue();
MainActivity.this.mMessages.add(data);
}
...
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
0
source to share