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() {
And then remove the listener in your onDestroy()
:
mDatabase.child(mPost_key).removeListener(mListener);
With reference of @Frank van Puffelen's answer. Change code to:
private ValueEventListener mListener;
mListener = mDatabaseRef.addValueEventListener(new ValueEventListener()
{...}
in onDestry() :
@Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mListener);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With