I'm developing an app in Android Studio and am using Firebase to store/retrieve data. This works fine, but when I save the retrieved data to a local variable and then attempt to display the data in a listview it doesn't work until I refresh the view.
This is my OnCreate function:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_chores);
//get database reference and user data
mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://...");
user = (User) getIntent().getSerializableExtra("user");
configureBackButton();
updateFromFirebase();
display();
}
This is the update function (variable map is a global var):
private void updateFromFirebase() {
final ArrayList<String> list;
final String name = user.getName().toLowerCase();
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot child : snapshot.getChildren()) {
ArrayList<String> list;
String name;
name = child.getKey();
list = (ArrayList)child.getValue();
map.put(name.toLowerCase(), list);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
...
}
});
list = map.get(name);
if(list==null) return;
final ListView list_xml = (ListView) findViewById(R.id.list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
list_xml.setAdapter(adapter);
}
And this is the display function:
private void display() {
final ArrayList<String> list;
final String name = user.getName().toLowerCase();
list = map.get(name);
if(list==null) return;
final ListView list_xml = (ListView) findViewById(R.id.list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
list_xml.setAdapter(adapter);
list_xml.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = adapter.getItem(position);
list.remove(item);
map.put(name, list);
CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
Snackbar sb = Snackbar.make(coordinatorLayout, "Item Removed!", Snackbar.LENGTH_SHORT);
sb.show();
adapter.notifyDataSetChanged();
}
});
}
Any insights to why it doesn't display the first time would be appreciated.