MMike
MMike

Reputation: 598

Prevent my MemoryLeak

i already come closer to solve my Memory leak by asking this question:

MemoryLeak trough onConfigurationChanged()

Now i know that my leak is caused by recreating the activity due to Rotation of the device.

I'm creating a reference to my searchbar in my activity:

searchbar = (EditText) findViewById(R.id.my_searchbar);

and pass this reference to my AsyncTask which is not an inner class of my Activity:

myWorkerClass.clearMemory();
    myWorkerClass = new WorkerClass(getApplicationContext(), gv, searchbar, width, scaleButtonText);
    myWorkerClass.execute();

In my AsyncTask i add a onTextChangedListener to my searchbar:

searchbar.addTextChangedListener(myTextWatcher);

When a orientation Change happens, i Need to call the AsyncTask again. To prevent MemoryLeaks i call clearMemory before which is a method of my AsyncTask:

public void clearMemory() {
    searchbar.removeTextChangedListener(myTextWatcher);

}

The Problem When onConfigurationChange() is called. I already got a new Activity created by the OS. That means my original reference to the searchbar isn't accessible/existing for me anymore. Therefore my clearMemory doesn't remove the textChangedListener from my searchbar... And then i start the AsyncTask again which adds another onTextChangedListener to my searchbar creating my Memory Leak.

My Question

How can i prevent this. (I would be really thankful for a code-snippet with a short Explanation).

How can i get the old reference after a new activity has been created. Or how can i call clearMemory() short time before a new Activity has been created by the OS due to Rotation of the device.

I Appreciated any help.

Update

Sorry i forgot to add my approaches to solve this issue:

I also tried to create a WeakReference:

WeakReference<EditText> myWeakReference = new WeakReference<EditText>(searchbar)

and put the reference to the AsyncTask like this:

myWorkerClass = new WorkerClass(getApplicationContext(), gv, myWeakReference.get(), width, scaleButtonText);
    myWorkerClass.execute();

Upvotes: 2

Views: 159

Answers (1)

Kelevandos
Kelevandos

Reputation: 7082

Create the SearchBar and TextWatcher on UI Thread and only invoke AsyncTasks in the TextWatcher when you need to obtain something (preferably passing some kind of listener to it). Like this:

SearchBar searchBar = (EditText) findViewById(R.id.my_searchbar);
searchBar.addTextChangedListener(myTextWatcher);

public class myTextWatcher implements TextWatcher {

    afterTextChanged(){
        /*   Invoke the AsyncTask here so it can retrieve data and return it through some listener /*

    }

}

Please also try adding the below parameter to your tag in the Manifest:

android:configChanges="orientation|screenLayout|screenSize|smallestScreenSize|navigation|uiMode"

It should prevent the activity from dying completely.

Upvotes: 0

Related Questions