I'm trying to display records saved in Firebase Database to the user in a ListView as The Application loads but it's not working. The problem is that when the app loads for the first time the contents are not added to the ListView.
As I'm testing the app I noticed that the contents are not displayed as I open the app for the first time but only if I close the app by pressing the back button and then reopen it.
I add this method: adapter.notifyDataSetChanged(); to the onStart() as suggested by some guy but it didn't work.
This is the method that fetches the data:
private void fetchData() {
if (FirebaseDatabase.getInstance() != null) {
FirebaseDatabase.getInstance().goOffline();
}
FirebaseDatabase.getInstance().goOnline();
Query query = FirebaseDatabase.getInstance().getReference().child("User");
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, new SnapshotParser<User>() {
@NonNull
@Override
public User parseSnapshot(@NonNull DataSnapshot snapshot) {
s = snapshot.getChildrenCount();
Toast.makeText(getApplicationContext(), Long.toString(s), Toast.LENGTH_SHORT).show();
return new User(snapshot.child("fullName").getValue().toString(),
snapshot.child("userId").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<User, MyViewHolder>(options) {
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.database_contents, parent, false);
return new MyViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i,
@NonNull User user) {
myViewHolder.setTxtFullName(user.getFullName());
myViewHolder.setTxtUserId(user.getUserId());
myViewHolder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
}
});
}
};
}
and this is where I made the call:
@Override
protected void onStart() {
super.onStart();
fetchData();
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
I also tried calling the fetchData() method in onCreate.
I will like the contents to be displayed in the ListView as the App loads for the first time. Thanks in advance