Reputation: 552
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:
OnResume()
OnPause()
of every Activity
, but the code will be duplicated in
every Activity
since it does the same job.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
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
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
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