0

I am trying to create a method to read my Firebase database in line with the rest of my code. I am trying to use a Reentrant Lock to do this, but it is not working. I want the output to be

---------- A
---------- B
---------- C
---------- D

upon calling updateMerchants(). Is there anyway I can make this work?

public static void updateMerchants()
{
    System.out.println("---------- A");
    lock.lock();
    DatabaseReference database = FirebaseDatabase.getInstance().getReference("users").child("merchants");
    database.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            System.out.println("---------- B");

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if (snapshot.exists()) {
                    System.out.println("----------exists");
                }
            }
            lock.unlock();
            System.out.println("---------- C");
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d("onCancelled: ", databaseError.toString());
        }
    });
    updateMerchantsUtil();
}

private static void updateMerchantsUtil()
{
    lock.lock();
    System.out.println("---------- D");
    lock.unlock();
}
  • 1
    So, what exactly is it doing that's different than what you expect? Please edit your question to explain in more detail. – Doug Stevenson Dec 07 '19 at 00:28
  • If your goal here is to try to make the database query block synchronously, that's not a strategy I recommend. It'll be better if you take up asynchronous programming techniques in order to better deal with Firebase APIs. – Doug Stevenson Dec 07 '19 at 00:29

1 Answers1

1

you can use the CountDownLatch , like follow:

System.out.println("---------- A");
CountDownLatch countDownLatch = new CountDownLatch(1);
@Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            System.out.println("---------- B");
            ..........
            System.out.println("---------- C");
            countDownLatch.countDown();
        }
private static void updateMerchantsUtil()
{
    countDownLatch.await();
    System.out.println("---------- D");
}
Benson
  • 66
  • 2