Home > database >  Asynctask Memory Leak Warning Android
Asynctask Memory Leak Warning Android

Time:11-17

I have created as asynctask to upload data to a server as below. But it shows this warning eaxctly at class AsyncTaskUploadClass. "This AsyncTask class should be static or leaks might occurs......" I have read and tried the weak reference style but i am unable to integrate it in this code. Any leads will be appreciated.

 public void ImageUploadToServerFunction(){
    final String imageName1 = GetImageNameEditText1.trim();
    final String userName = GetUserName.trim();
    final String imageView1 = getStringImage1(bitmap1);
  
    class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(UploadActivity.this,"Your Data is Uploading....",false,false);
        }
        @Override
        protected void onPostExecute(String string1) {
            super.onPostExecute(string1);
            progressDialog.dismiss();
         }
        @Override
        protected String doInBackground(Void... params) {
            ImageProcessClass imageProcessClass = new ImageProcessClass();
            HashMap<String,String> HashMapParams = new HashMap<>();
            HashMapParams.put(ImageName1, imageName1);
            HashMapParams.put(UserName, userName);
            HashMapParams.put(ImagePath1, imageView1);
            return imageProcessClass.ImageHttpRequest(ServerUploadPath, HashMapParams);
        }
    }
    AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
    AsyncTaskUploadClassOBJ.execute();
}

CodePudding user response:

It's in the nature of inner classes of Java- a class within a class has a hidden reference to the parent instance. That can cause memory leaks. The way to avoid that is to make it a static inner class- static class Foo. This will cause it to remove the hidden reference, but the inner class will no longer be able to reference functions or member variables of the parent.

More practically- this type of AsyncTask, while it technically can cause a temporary leak, is fairly safe as long as the doInBackground function terminates in a reasonable amount of time. For this class, if imageProcessClass.ImageHttpReques() runs and terminates (with either a timeout error or by finishing its work) in a reasonable amount of time it isn't a leak worry- it just that the parent class, which looks like an Activity, will not be freed until it does so. So it will force the parent class to stick around for a second or two longer than needed if the Activity is finished but the request is processing.

  • Related