kidsoul kidsoul - 26 days ago 7
Android Question

Cannot get list size from Firebase on Android

My log can print all

Exercise
object. But
listExercise
is null when I call. What's the problem?

ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Exercise exercise = postSnapshot.getValue(Exercise.class);
String temp = exercise.toString();
Log.d("exercise: ", temp + "\n"); // can log all
listExercises.add(exercise);
}
}

@Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("The read failed: ", firebaseError.getMessage());
}
});
Log.d("LISTSIZE: ", String.valueOf(listExercises.size())); // return 0


[UPDATE] The answer for anyone need:

@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Exercise exercise = postSnapshot.getValue(Exercise.class);
listExercises.add(exercise);
}
// action with data here
Exercise ex = listExercises.get(0);
tvQuestion.setText(ex.getQuestion);
}

Answer

When the method "paintListInScreen" is called, you know for sure the list have some content (or maybe not, that depends on the server, but you are being consistent with threads).

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
            Exercise exercise = postSnapshot.getValue(Exercise.class);
            String temp = exercise.toString();
            Log.d("exercise: ", temp + "\n"); // can log all
            listExercises.add(exercise);
        }
         Log.d("LISTSIZE: ", String.valueOf(listExercises.size())); // return 0
        paintListInScreen(listExercises);
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
        Log.d("The read failed: ", firebaseError.getMessage());
    }
});