AsyncTask without leaks

AsyncTask without leaks

By : Thayná
Date : November 19 2020, 03:01 PM
it helps some times I understood.
AsyncTask should be static AsyncTask move to -> companion object {}. WeakReference - For AsyncTask without leak (Good exp.)
code :
override fun onPause() {
        when {
            placesTask != null -> {
                placesTask = null
            setPlacesTask != null -> {
                setPlacesTask = null

    private fun downloadUrl(strUrl: String): String {
        var data = ""
        var iStream: InputStream? = null
        var urlConnection: HttpURLConnection? = null
        try {
            urlConnection = URL(strUrl).openConnection() as HttpURLConnection
            iStream = urlConnection.inputStream
            val br = BufferedReader(InputStreamReader(iStream!!))
            val sb = StringBuilder()
            var line: String? = null
            while ({line = br.readLine(); line }() != null) sb.append(line)
            data = sb.toString()
        } catch (e: Exception) {
            Log.d("downloading url", e.toString())
        } finally {
            if (iStream != null) iStream.close()
            if (urlConnection != null) urlConnection.disconnect()
        return data

companion object {
    var placesTask: PlacesTask? = null
    var setPlacesTask: SetPlaceTask? = null

    class PlacesTask(mainActivity: MainActivity) : AsyncTask<String, Int, String>() {
            private val mRef: WeakReference<MainActivity> = WeakReference(mainActivity)

            override fun doInBackground(vararg url: String): String? {
                var data: String? = null
                try {
                    data =  mRef.get()?.downloadUrl(url[0])
                } catch (e: Exception) {
                    Log.d("Background Task", e.toString())
                return data

            override fun onPostExecute(result: String) {
                setPlacesTask = SetPlaceTask(mRef.get()!!).execute(result) as SetPlaceTask?

        class SetPlaceTask(mainActivity: MainActivity) : AsyncTask<String, Int, List<HashMap<String, String>>>() {
            private val mRef: WeakReference<MainActivity> = WeakReference(mainActivity)

            override fun doInBackground(vararg jsonData: String): List<HashMap<String, String>>? {
                var places: List<HashMap<String, String>>? = null
                try {
                    places = PlaceJSONParser().parse(JSONObject(jsonData[0]))
                } catch (e: Exception) {
                    Log.d("Exception", e.toString())
                return places

            override fun onPostExecute(list: List<HashMap<String, String>>) {
                for (i in list.indices) {
                    val hmPlace = list[i]
                    mRef.get()?.parkingLatLng = LatLng(hmPlace["lat"]!!.toDouble(), hmPlace["lng"]!!.toDouble())
                    mRef.get()?.mMarkerPlaceLink!!.put(mRef.get()?.map!!.addMarker(MarkerOptions().icon(mRef.get()?.vectorToBitmap(R.drawable.ic_local_parking_black_12dp, ContextCompat.getColor(mRef.get()?.applicationContext, R.color.colorPrimaryDark))).position(mRef.get()?.parkingLatLng!!).title(hmPlace["place_name"] + "\n" + hmPlace["vicinity"])).id, hmPlace["reference"].toString())

Share : facebook icon twitter icon
Will running AsyncTask within AsyncTask cause memory leaks?

Will running AsyncTask within AsyncTask cause memory leaks?

By : countduckula
Date : March 29 2020, 07:55 AM
wish helps you
I was wondering that if I use execute() inside the onPostExecute() function (...)
Warning: This AsyncTask class should be static or leaks might occur

Warning: This AsyncTask class should be static or leaks might occur

By : AlfaRanger
Date : March 29 2020, 07:55 AM
this will help Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.
To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)

This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)

By : Arval Headrick
Date : March 29 2020, 07:55 AM
To fix the issue you can do Create a separate class that implements AsyncTask, then in your activity instantiate it, and run the execute method.
Android context leaks in AsyncTask

Android context leaks in AsyncTask

By : o9o9o
Date : March 29 2020, 07:55 AM
may help you . If I understand your question correctly: Java's WeakReference or SoftReference class is a good fit for this type of situation. It will allow you to pass the context to the AsyncTask without preventing the GC from freeing the context if necessary.
The GC is more eager when collecting WeakReferences than it is when collecting SoftReferences.
Android AsyncTask memory leaks

Android AsyncTask memory leaks

By : Strassi
Date : March 29 2020, 07:55 AM
this one helps.
Cancelling is a good way to solve your memory leak. You might want to consider cancelling in onStop though, since you set up a new task in onStart. You might want to combine this with dismissing the progressDialog in onStop, since you're cancelling the task.
Related Posts Related Posts :
  • How to set epoch in Firestore using server time
  • Android 8 Geofences on killed app
  • When I Try to Change the Color of SnackBar TextView App Crashes
  • cannot access outer class variable for datasnapshot.haschild() method
  • Cannot read image written to file
  • Databinding seems to be broken after adding Room
  • switch statement Error : Statement must be prepended with case label
  • View local firebase database with Stheto on Android
  • How to employ keyed-hash message authentication code (HMAC) with Android Keystore
  • Prevent inviting existing users or previously invited
  • How to overwrite windowSoftInputMode using edit-config tag in cordova
  • Difference between Loader and AsyncTask
  • In Firebase Android, retrieve the value of a child node and save it in a boolean variable
  • when i scroll the custom list in my android app then the favorite icon which is part of the custom adapter changes on it
  • adding room dependency gives manifest merge error
  • Visibility of RelativeLayout change on scrolling Gridview
  • Strange LiveData behavior vs ObservableField
  • Which layout is used for clash of clans home screen? We can scroll it horizontal as well as vertical. Please illuminate
  • RxJava: Know when observable is finished and return Boolean Observable to the caller
  • how to use savedInstanceState to save camera information when the orientation change occure
  • Style React-Native via Styles.xml
  • Keyboard won't show after calling InputMethodManager.showSoftInput
  • Compiling ffmpeg for Android on OSX
  • Button does not get clicked on the first attempt
  • AR Core performance, learning curve and comparison with other frameworks
  • Codename one : Attaching images to email message fails
  • Error: Unsupported type 'viewItem' in Android build
  • setLayoutParams on ConstraintLayout does not change size
  • How to profile the fetch time of the android gradle libraries
  • Kotlin setOnclickListener
  • Naming convention for methods returning RxJava's Completable
  • Conv3D not working
  • FFmpeg audio video merge command
  • Do you have to use gradle-experimental for JNI?
  • How to get key hashes for facebook for facebook app?
  • ZXing not calling onActivityResult, When scanning QR Code
  • Integration of Android Native module with existing Xamarin Native Project
  • Restore RecyclerView state after rotating
  • ViewModelProviders java.lang.RuntimeException trying to instantiate class which inherit AndroidViewModel
  • SKD19 vs SDK24 - Usage of API documented as @since 1.8+
  • filter option in list view fragment activity
  • Picture from camera not showing up in second activity
  • How to change imageview according to screen size
  • How to copy Android Studio project to remote Git (NOT GitHub) server
  • How to get React-Native to announce specific accessibility message via AccessibiliyManager?
  • Change colors of com.tech.freak.wizardpager.ui.StepPagerStrip
  • Android fullscreen activity shows ActionBar
  • Turn on the screen when timer calls onFinish()
  • Would like a bit of clarification with SQLite database's onUpgrade method
  • Use ObjectBox with Libgdx
  • How to make combine Gregorian and Hijri calendar in Android?
  • Try to read text file from sdcard in other language
  • "App not installed" message when installed apk
  • How to execute a designated test suite class in Firebase Test Lab
  • play music with background service
  • background not visible on LG G3
  • should every View have an id?
  • Realm object server sync on low connection.
  • Correct way to add more views to adapter
  • Getting error in android support library
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org