如何在OnDestroy(Android Firebase)中删除此侦听器? [英] How do I remove this listener in OnDestroy (Android Firebase)?
本文介绍了如何在OnDestroy(Android Firebase)中删除此侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在OnCreate方法中的ValueEventListener。我想摧毁这是OnDestroy方法,因为它可能导致内存泄漏,我也读过它,这是一个很好的做法。
This is my ValueEventListener in OnCreate method. I want to destroy this is OnDestroy method because it might be causing memory leak and also I've read it that it's a good practice to do so.
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
display_author = (String) dataSnapshot.child("author").getValue();
display_quote = (String) dataSnapshot.child("quote").getValue();
display_pic_url = (String) dataSnapshot.child("pic_url").getValue();
categoryData=(String) dataSnapshot.child("catg").getValue();
display_prof=(String) dataSnapshot.child("prof").getValue();
copyQuote = (display_quote + " - " +display_author);
try {
author.setText(display_author);
quote.setText(display_quote);
category.setText(categoryData);
profession.setText(display_prof);
Glide.with(SingleExploreQuotes.this).load(display_pic_url).override(192, 192).into(profile_img);
} catch (Exception e) {
finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
推荐答案
当您注册侦听器时,给听众。将该监听器保留在成员字段中:
When you register the listener, you get back a handle to the listener. Keep that listener in a member field:
private ValueListener mListener;
mListener = mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
然后移除你的 onDestroy()
中的监听器:
And then remove the listener in your onDestroy()
:
mDatabase.child(mPost_key).removeListener(mListener);
这篇关于如何在OnDestroy(Android Firebase)中删除此侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文