1

I'm trying to write a method to fetch all of the current saved students in my firebase database. But I wasn't able to store these data on the global variable students. How to do that? I couldn't figure out how to fix this scope problem it with OOP's theory. Any brilliant idea, please?

    private static ArrayList<StudentModel> students = new ArrayList<StudentModel>();
    private Firebase mStudentsRef;

    public ArrayList<StudentModel> getAll() {
        mStudentsRef = new Firebase("https://firstapp.firebaseIO.com/students");
        mStudentsRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                StudentModel student;
                HashMap<String, String> studentDetails;
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    studentDetails = new HashMap<String, String>();
                    student = new StudentModel();
                    for (DataSnapshot sds : ds.getChildren())
                        studentDetails.put(sds.getKey(), sds.getValue().toString());
                    student.set_id(ds.getKey());
                    student.setFirstname(studentDetails.get(dbHandler.STUDENT_FIRSTNAME));
                    student.setLastname(studentDetails.get(dbHandler.STUDENT_LASTNAME));
                    student.setUsername(studentDetails.get(dbHandler.STUDENT_USERNAME));
                    student.setPassword(studentDetails.get(dbHandler.STUDENT_PASSWORD));
                    students.add(student);
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.e("Student.getAll(): ", firebaseError.getMessage());
            }
        });
        return students;
    }

Thanks in advance!

  • @MartinSerrano no it doesn't. – shmosel Apr 18 '16 at 21:47
  • You cannot return something now that is still being loaded (asynchronously). See http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Apr 18 '16 at 22:14
  • The answer is don't! Wait for the data to load in all cases that you would use it. If you try to set it to a global variable and use it elsewhere, you'll run into race conditions and bugs. Use an event driven model or a promise based strategy instead. – Kato Apr 19 '16 at 02:06
  • @Kato, I need that data for external treatment and display into a recycler view! – James Kouga Apr 19 '16 at 06:14

1 Answers1

0

You can create a private method that take ArrayList<StudentModel> as argument and then you can set the students global variable to that data coming through argument. I hope that should work and would be clean solution.

You need to have another local ArrayList<StudentModel> type variable in addValueEventListener. I hope it is clear.

If you need example, let me know

JNI_OnLoad
  • 5,472
  • 4
  • 35
  • 60