This is my first post, so if I did not follow some protocol, I had to apologize.
I am trying to populate a ListView with some information from my Firebase database. I think the problem that I encountered is that the database query is too slow (the thread is probably loading images), and my activity is loading its activity layout, without waiting for the stream to complete. (If I go through the debugger and wait a bit, I will eventually see the information that I will parse: usernames, user numbers and user images). Everything I requested suggests that I should use AsyncTask for this. Unlike using thread lock or b / c semaphore, AsyncTask is thread safe.
As I understand it, Firebase requests are already running asynchronously; therefore, the doInBackground method for AsyncTask, which I "tried" to implement, seems redundant. Also, I'm a little confused by the overloaded AsyncTask signature and the call: new someTask.execute ("some things on the line").
Any suggestions on how I can do this? Any feedback is greatly appreciated!
// Please ignore the minor indent from pasting my code in
protected void onCreate(Bundle savedInstanceState) {
...
new getFirebaseInfoTask();
}
private class getFirebaseInfoTask extends AsyncTask {
@Override
protected Object doInBackground(Object... args) {
userInfoList = GetUserInfoFromFirebase.getUserInfo();
return userInfoList;
}
@Override
protected void onProgressUpdate(Object... args) {
populateUserInfoList();
}
}
private void populateUserInfoList() {
Collections.addAll(userInfoList);
populateFriendsListView();
}
private void populateFriendsListView() {
ArrayAdapter<UserInfo> adapter = new MyListAdapter();
ListView listView = (ListView) findViewById(R.id.friends_listview);
listView.setAdapter(adapter);
registerClickCallBack();
}
...
public class GetUserInfoFromFirebase {
public static ArrayList getUserInfo() {
final ArrayList<UserInfo> list = new ArrayList<UserInfo>();
Firebase firebase = new Firebase("https:......firebaseio.com");
firebase.child("users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
HashMap<String, Object> users = (HashMap<String, Object>) snapshot.getValue();
for(Object user : users.values()) {
HashMap<String, Object> userMap = (HashMap<String, Object>) user;
String userNumber = (String) userMap.remove("number");
if(!list.contains(userNumber)) {
String name = (String) userMap.remove("username");
String pic = (String) userMap.remove("profile_picture");
UserInfo info = new UserInfo(userNumber, name, pic);
list.add(info);
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
return list;
}
source
share