Handle Data Returned By An Async Task (firebase)
I am trying to figure out how to do something with data returned from an AsyncTask. I have an activity where I am calling an async Firebase get operation (operation existing in a d
Solution 1:
What you are looking for is Callback interface, as for your needs you need simple interface that implement single method with single parameter, as there is no out of the box convention for Java 6 (Android Java version) you can easily create it by yourself:
interfaceCallback {
voidact(List<AttendModel> models);
}
pass it as an argument to the firebase wrapping method, and call it with the result.
publicvoidgetAllAttendeesFor(String UUID, final ArrayList<AttendModel> attendArray, final Callback callback) {
final DatabaseReference attendObjects = getDatabaseTableWith(Constants.tableAttendObject);
Query queryRef = attendObjects.orderByChild(Constants.taAttendObjectUUID).equalTo(UUID);
queryRef.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
HashMap<String, Object> attend = (HashMap<String, Object>) postSnapshot.getValue();
StringUUID = (String) attend.get(Constants.AttendObjectUUID);
String userUsername = (String) attend.get(Constants.AttendObjectUserUsername);
AttendModel attendModel = newAttendModel(userUsername, UUID);
attendArray.add(attendModel);
callback.act(attendArray)
}
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
}
});
}
then in your upper level method:
publicvoidgetAttendants() {
ArrayList<AttendModel> attendees = newArrayList<AttendModel>();
FirebaseConnection.getInstance().getAllAttendeesFor(uuid, attendees,
new Callable<List<AttendModel) {
voidact(List<AttendModel> attendees){
//here you can update the UILog.d("attendees", String.valueOf(attendees.size()));
}
};
}
Just be aware that you can update the UI only if onDataChange method of the firebase query is called on the main thread.
Post a Comment for "Handle Data Returned By An Async Task (firebase)"