Khaled
Khaled

Reputation: 552

Android: using one Firebase ChildEventListener through my app

I'm looking for a way to listen to a particular location in my database in every activity using one ChildEventListener.

I have a shopping app, and I need to listen to the user's order status through the app to show alerts and save data locally.

I had 2 ideas in mind:

  1. I thought about attaching and detaching the listener in OnResume()
    and OnPause() of every Activity, but the code will be duplicated in every Activity since it does the same job.
  2. I thought about attaching one listener to the MainActivity, then send broadcasts to other activities, but this failed due to MainActivity being destroyed

--

What is the best practice for listening to one node and keep app synchronized?

Upvotes: 0

Views: 549

Answers (3)

Marcus
Marcus

Reputation: 793

recently I solved a same problem. So, make a handler class of the ChildEventListener and its has a single instance like FirebaseDatabase, FirebaseAuth and others Firebase services. That class is the same this snippet:

public class ShopHandler implements ChildEventListener {

    private static ShopHandler current = null;
    private DatabaseReference databaseReference;

    private ShopHandler() {}

    public synchronized static void attach() {
        if (current = null) {
            current = new ShopHandler();
            databaseReference = FirebaseDatabase.getInstance().getReference("data/yournode");
            databaseReference.addChildEventListener(this);
        }
    }

    public syncrhonized static void detach() {
         // remove listeners and set current as null
    }
    // implements all methods about ChildEventListener

}

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

There is no problem in Firebase when using multiple listeners, even if it's the same listener. As long as you remove the listener according to the life-cycle of your activities, Firebase will handle almost perfectly the listeners.

Your class should look like this:

public class HelperClass extends Application {
    private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    public static verifyStatus() {
        databaseReference.addChildEventListener() /* ... */
    }
}

You need to remove the listener accordingly to the life-cycle of your activity. If you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy. But remember onDestroy is not always called.

Hope it helps.

Upvotes: 1

Bruno Ferreira
Bruno Ferreira

Reputation: 1571

Try this way create a class and inside class create the method that you want like that:

public class firebaseutils {

public static void check(){

    }

}

And call this class where you want, like that:

firebaseutils.check();

Upvotes: 0

Related Questions