본문 바로가기
모바일개발(Mobile Dev)/안드로이드개발(Android)

memory leak in asynctask

by 테크한스 2017. 9. 10.
반응형


https://stackoverflow.com/questions/23594332/android-new-intent-causes-nullpointerexception-in-asynctask




Sounds to me like a memory leak. Always use WeakReferences in AsyncTasks when passing a Context or Activity or other such objects to it. Try something like this:

public class ExampleAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private final WeakReference<Context> contextReference;

    public ExampleAsyncTask(Context context) {
        this.contextReference = new WeakReference<Context>(context);
    }

    @Override
    protected Boolean doInBackground(Void... params) {

        Context context = this.contextReference.get();
        if(context != null) {
            // Do your work
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

        Context context = this.contextReference.get();
        if(context != null) {
            // Do your work
        }
    }
}

What the WeakReference does is to allow for the object it is referencing to be garbage collected. If you hold the reference directly the object cannot be garbage collected and this can cause memory leaks in Threads and AsyncTasks. This would for example happen when you hold a Contextreference directly and the Activity from which the Context object comes is recreated, for example when you rotate your device or the Activity is in the background for some time.

In the example above you save the Context object in a WeakReference, and every time you want to use the Context you first have to get it from the WeakReference. After you got it from the WeakReference you can simply check if it is null or not. If it is not null than it is safe to work with the Context. If it is null than the Context or the corresponding Activity have already been garbage collected and are not usable anymore.

shareimprove this answer



반응형

'모바일개발(Mobile Dev) > 안드로이드개발(Android)' 카테고리의 다른 글

android icon guide  (0) 2017.09.10
notification text font color  (0) 2017.09.10
제품(Products) 탭  (0) 2017.09.02
oAuth의 인증 플로우  (0) 2017.09.02
Invalid_grant  (0) 2017.09.02