Am trying to build and return ArrayList
from firebase DataSnapshot
.
My database structure
I have this ListItem Class.
public class ListItem {
private String title;
private String message;
private String image;
private String type;
private String userid;
public String getTitle() {return title;}
public String getMessage() {return message;}
public String getImage() {return image;}
public String getType() {return type;}
public String getUserid() {return userid;}
public void setTitle(String title) {this.title = title;}
public void setMessage(String message) {this.message = message;}
public void setImage(String image) {this.image = image; }
public void setType(String type) {this.type = type; }
public void setUserid(String userid) {this.userid = userid;}
}
I have this loadNotificationDatabase
method for testing which is working fine.
private ArrayList loadNotificationDatabase() {
ArrayList<ListItem> results = new ArrayList<>();
ListItem user1 = new ListItem();
user1.setTitle("Suresh Dasari");
user1.setMessage("Team Leader");
user1.setUserid("Hyderabad");
results.add(user1);
ListItem user2 = new ListItem();
user2.setTitle("Rohini Alavala");
user2.setMessage("Agricultural Officer");
user2.setUserid("Guntur");
results.add(user2);
ListItem user3 = new ListItem();
user3.setTitle("Trishika Dasari");
user3.setMessage("Charted Accountant");
user3.setUserid("Guntur");
results.add(user3);
return results;
}
Now I tried to load data from firebase database and return array list, but it doesn't return anything its always empty array and no error. I know that am not getting the code right, please can anyone assist me?
public ArrayList loadNotificationDatabase() {
String userSessionId = "QvdfKO9ek4qlPZJA";
ArrayList<ListItem> list = new ArrayList<>();
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ListItem users = new ListItem();
users.setTitle(ds.child("title").getValue(String.class));
users.setMessage(ds.child("message").getValue(String.class));
users.setUserid(ds.child("user_id").getValue(String.class));
list.add(users);
String message = ds.child("message").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String type = ds.child("type").getValue(String.class);
String image = ds.child("image").getValue(String.class);
String user_id = ds.child("user_id").getValue(String.class);
Log.d("loadNotification", title + " / " + message + " / " + type + " / " + image + " / " + user_id);
}
Log.e("loadNotification", list.toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DatabaseError", databaseError.getMessage());
}
};
notificationDatabase.child(userSessionId).addListenerForSingleValueEvent(valueEventListener);
return list;
}
ArrayList userList = loadNotificationDatabase();
Log.e("userLists", userList.toString());