0

I was trying to take the all the key values as String and add them to "studentrolls" Arraylist and trying to return the Arraylist so that I can make Multiple choice Dialog box. But somehow its not adding to any element to the arraylist. Here's my code:

public ArrayList < String > getAllstudents(String coursename) {
  rootnode = FirebaseDatabase.getInstance();
  String uniqueid = coursename + ID;
  reference = rootnode.getReference().child("Course").child(uniqueid).child("students");
  studentrolls = new ArrayList < String > ();
  Log.d(TAG, "Teachers ID:  " + ID);
  reference.addValueEventListener(new ValueEventListener() {

    @SuppressLint("LongLogTag")@Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
      Log.d(TAG, "onDataChange: " + snapshot + "");
      Log.d(TAG, "onDataChange: " + snapshot.getValue() + "");
      Log.d(TAG, "Checking snapshot: " + snapshot.getChildren().toString());
      for (DataSnapshot ds: snapshot.getChildren()) {

        Log.d(TAG, "Students roll:    " + "" + ds.getKey());
        Log.d(TAG, "Data type" + ds.getKey().getClass().getName());
        studentrolls.add(ds.getKey());

        //Log.d(TAG, "Teachers ID from firebase: " + teID);
      }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
      Log.d(TAG, "Fetching data was failed");

    }
  });
  Log.d(TAG, "Inside mydatabae helper array list=====" + studentrolls.size());;

  return studentrolls;
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Shakib
  • 13
  • 5
  • I can provide you with logs if u want to see that too – Shakib Nov 08 '20 at 18:50
  • Most likely you're being bitten by the fact that retrieving data from Firebase (as from most modern cloud APIs) happens asynchronously, and your `studentrolls` happens before any `studentrolls.add(ds.getKey())` ever happens. You can check this from the log output. The conclusion is always the same: any code that needs data from the database needs to be inside `onDataChange` or be called from there. See my answer here for a longer explanation and example: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Nov 08 '20 at 21:19

0 Answers0