[英]Null pointer with Firebase auth. How to put listener to another class
[英]Can I put Firebase ValueEvent listener in Application class
我想在5個活動中使用Firebase Value事件偵聽器。 而且所有偵聽器都將執行相同的工作,因此我可以將偵聽器放在Application類中,並在應用程序終止時刪除偵聽器嗎?
public class MyApplication extends Application {
private RefWatcher refWatcher;
private ValueEventListener value_event_listener;
public static RefWatcher getRefWatcher(Context context) {
MyApplication application = (MyApplication) context.getApplicationContext();
return application.refWatcher;
}
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
EmojiManager.install(new IosEmojiProvider());
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
refWatcher = LeakCanary.install(this);
value_event_listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//TODO
}
@Override
public void onCancelled(DatabaseError databaseError) {
//TODO
}
};
FirebaseDatabase.getInstance().getReference().child(C.DELIVERY).addValueEventListener(value_event_listener);
}
@Override
public void onTerminate() {
super.onTerminate();
FirebaseDatabase.getInstance().getReference().child(C.DELIVERY).removeEventListener(value_event_listener);
}
}
簡短的回答,是的,但是有一種更清潔的方法來解決它。
SOLID的一種更有效的方法是創建一個實用程序類,該類從您要偵聽此事件的每個位置調用。 這樣,您可以在將來更改需求時擴展實用程序類。 然后可以應用更改,而不會潛在地影響使用該更改的所有位置。
這也使它更具可測試性,因為您可以模擬出實用程序類以驗證不同的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.