Skip to content

Instantly share code, notes, and snippets.

@amritlalsahu5
Created February 15, 2020 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amritlalsahu5/4c1de1ea5338cffe0be822e2c5789a1e to your computer and use it in GitHub Desktop.
Save amritlalsahu5/4c1de1ea5338cffe0be822e2c5789a1e to your computer and use it in GitHub Desktop.
package com.codehangouts.sampleapp.memoryleak.kotlin.innerasynctask
import android.os.AsyncTask
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.R
import java.lang.ref.WeakReference
class InnerAsyncTaskReferenceActivity : AppCompatActivity() {
/*
* Following mistakes should be avoided in this scenario.
* Mistake 1. Try to avoid referencing a class inside an activity because normal inner class holds implicit reference of parent class.
* If at we need to do it,make it private static class which does not hold any implicit reference.
* Mistake 2. Never use a direct reference of a view, reference of Activity itself or context from activity inside an Asynctask.
* Mistake 3. Specially in case of AsycTask Inner class : We should always cancel the asyncTask inside onDestroy of Activity because the asyncTask will still be running even if the activity
* is destroyed preventing activity to be garbage collected.
*
* */
private val textView: TextView? = null
private var backgroundOperation: BackgroundOperation? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.inner_async_task_activity)
/*
* Initiate & execute AsyncTask here!
* */
backgroundOperation = BackgroundOperation(textView)
backgroundOperation!!.execute()
}
private inner class BackgroundOperation internal constructor(textView: TextView) : AsyncTask<Void, Void, String>() {
//private View view;
private val viewWeakReference: WeakReference<TextView>
init {
//this.view = view; // Problem 2
// Instead use WeakReference
this.viewWeakReference = WeakReference(textView)
}
override fun doInBackground(vararg voids: Void): String {
try {
Thread.sleep(5000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
return "The task is completed!"
}
override fun onPostExecute(value: String) {
super.onPostExecute(value)
//textView.setText(s);
val view = viewWeakReference.get()
if (view != null) {
view.text = value
}
}
}
override fun onDestroy() {
super.onDestroy()
/*
* Always cancel AsyncTask when activity is destroyed.
*/
if (backgroundOperation != null) {
backgroundOperation!!.cancel(true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment