Please have a look at the code below:
public class MyGridFragment extends Fragment{
Handler myhandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case 2: {
ArrayList<HashMap<String,String>> theurls = (ArrayList<HashMap<String,String>>) message.obj;
urls.addAll(theurls);
theimageAdapter.notifyDataSetChanged();
dismissBusyDialog();
break;
}}}};
}
When I use handler like this I get a warning "handler should be static, else it is prone to memory leaks." Can someone tell me what is the best way to do this?
I run into the same issue and I find that it is one of this topics with many questions and few answeres. My solution is simple and I hope it can help someone:
We can create a static Handler subclass that simply runs a Runnable. The actual handler instance will know what to do through the runnable that will have access to instance variables.
The warning is gone while the funcionality is the same.
I recently updated something similar in my own code. I just made the anonymous Handler class a protected inner class and the Lint warning went away. See if something like the below code will work for you:
You may have to change where I put "theFrag." as I could only guess as to what those referenced.
A simple solution for this case might be:
Per the ADT 20 Changes, it looks like you should make it static.
Here's a somewhat useful little class I made that you can use. Sadly it's still quite verbose because you can't have anonymous static inner classes.
If you read docs about AccountManager or PendingIntent, you will see that some methods take Handler as one of arguments.
For example:
Imagine the situation. Some Activity calls PendingIntent.send(...) and put the non-static inner subclass of Handler. And then activity is destroyed. But inner class lives.
Inner class still holds a link to destroyed activity, it cannot be garbage-collected.
If you're not planning to send your handler to such methods, you have nothing to worry about.