Skip to content Skip to sidebar Skip to footer

How To Handle Asynchronous Database With Firebase?

I have a lot of questions about handeling asynchronous database in my Android app. Since I know that database is asynchronous, I've tried several things to handle it. As you can se

Solution 1:

Change this:

   myReff.addValueEventListener(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {

            //this will be executed only if my array is changed (So only if my other function have been correctly executedsetAnotherArray(array_from_database);
            System.out.println("3");
        }

to this:

final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myReff = database.getReference();

  myReff.addValueEventListener(new ValueEventListener() {
        @Override
        publicvoid onDataChange(DataSnapshot dataSnapshot) {

          DatabaseReference ref2 = database.getReference();

          //Take the array from my database (gived in parameter)final ArrayList<Integer> array = array_from_database;
           System.out.println("2");

        array.set(0,3);

        Map<String, Object> chemainChild = new HashMap<>();
        chemainChild.put("server/user/",array);

        myReff.updateChildren(chemainChild);

            System.out.println("3");
        }

Some code may be missing from the above, but you get the idea add the code that is in the method public void setArray_for_database(ArrayList<Integer> array_from_database){ for this to work.

Since onDataChange is asynchronous meaning the program will keep executing, even if data is still not retrieved then this is the only way.

The reason you get 1-3-2, is because of this:

  1. It entered the first onDataChange
  2. It printed "1"
  3. It entered the second onDataChange that is inside the first.
  4. It printed "3" since it is asynchronous, then when the data was retrieved
  5. It called the method and printed "2"

So the best thing is to add the data in the method inside the onDataChange

The above will fix the asynchronous problem that you had in the question. But you really should denormalize your data.

Read this to learn more: https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html

Post a Comment for "How To Handle Asynchronous Database With Firebase?"