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?
A memory leak happens when memory is allocated but never freed. This means the GC is not able to take out the trash once we are done with the takeout. Android has a 16ms drawing window, and the GC normally takes less time to deal with memory.
If this occurs frequently or repeatedly over an extended period of time, a large number of handles may be marked in-use and thus unavailable, causing performance problems or a crash. The term is derived from memory leak. Handle leaks, like memory leaks, are specific instances of resource leaks.
The Memory Profiler is a component in the Android Profiler that helps you identify memory leaks and memory churn that can lead to stutter, freezes, and even app crashes. It shows a realtime graph of your app's memory use and lets you capture a heap dump, force garbage collections, and track memory allocations.
A memory leak happens when the stack still refers to unused objects in the heap.
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:
public class MyGridFragment extends Fragment{ static class MyInnerHandler extends Handler{ WeakReference<MyGridFragment> mFrag; MyInnerHandler(MyGridFragment aFragment) { mFrag = new WeakReference<MyGridFragment>(aFragment); } @Override public void handleMessage(Message message) { MyGridFragment theFrag = mFrag.get(); switch (message.what) { case 2: ArrayList<HashMap<String,String>> theurls = (ArrayList<HashMap<String,String>>) message.obj; theFrag.urls.addAll(theurls); theFrag.theimageAdapter.notifyDataSetChanged(); theFrag.dismissBusyDialog(); break; }//end switch } } MyInnerHandler myHandler = new MyInnerHandler(this); }
You may have to change where I put "theFrag." as I could only guess as to what those referenced.
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