Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove this listener in OnDestroy (Android Firebase)?

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) {
        }
    });
like image 679
Shahid Shaikh Avatar asked Dec 10 '16 09:12

Shahid Shaikh


2 Answers

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);
like image 50
Frank van Puffelen Avatar answered Jan 19 '23 18:01

Frank van Puffelen


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);
    }
like image 23
sabith.ak Avatar answered Jan 19 '23 18:01

sabith.ak