2

Sorry if this seems a basic question. I've updated Android Studio and notice some memory leak warnings on my AsyncTasks saying I should make them static. I have made them static but can't seem to make anything like List, ProgressBar, ImageView work without getting the same memory leak warning. It seems I can't win no matter which way I try it. I guess my questions are:

  1. Are AsyncTasks supposed to be static? The official documentation doesn't make it static but my IDE fires warnings saying they should.

  2. If they are meant to be static, how can I start and stop a ProgressBar within the static AsyncTask.

EDIT

This still throws "This AsyncTask class should be static or leaks might occur"

private class DownloadCategoryTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {

        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

        String url = Config.API_URL +
                "/Index.aspx?" +
                "type=3&" +
                "site_id=" + SITE_ID;

        String method = "GET";

        String array_name = "categories";

        Downloaded_category_array = Config.getJSONNew(url, method, array_name, context);

        return "";

    }

    protected void onPostExecute(String result) {

        if(isCancelled()){
            return;
        }

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Update your UI here
                //showProgressBar();
            }
        });

        Populate_category_list();
    }
}
ScottC
  • 162
  • 1
  • 14

3 Answers3

1

Try this solution which I found:

public class MainActivity extends AppCompatActivity {
   private ProgressBar progressBar;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      progressBar = findViewById(R.id.progress_bar);
   }

   public void startAsyncTask(View v) {
      ExampleAsyncTask task = new ExampleAsyncTask(this);
      task.execute(10);
   }

    private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
       private WeakReference<MainActivity> activityWeakReference;

       ExampleAsyncTask(MainActivity activity) {
          activityWeakReference = new WeakReference<MainActivity>(activity);
       }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        MainActivity activity = activityWeakReference.get();
        if (activity == null || activity.isFinishing()) {
            return;
        }

        activity.progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(Integer... integers) {
        for (int i = 0; i < integers[0]; i++) {
            publishProgress((i * 100) / integers[0]);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "Finished!";
     }
  }
}

Reference: here

Sandeep Yohans
  • 929
  • 1
  • 14
  • 36
0

No, No need to make AsyncTasks as static.

If non static methods are trying to modify static members then IDE throws warning to make it static.

If you want to update your UI from AsyncTask use 'runOnUiThread'.

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Update your UI here
                showProgressBar();
            }
        });
Chandrakanth M
  • 299
  • 1
  • 4
  • 10
  • If non static methods are trying to modify static members then IDE throws warning to make it static. -- Is this true? I commented out everything in AsyncTask and the warning is still there? – ScottC Jan 03 '18 at 15:40
  • Sorry for the slow reply, completely forgot about this. I ended up switching to Volley in the end. – ScottC Mar 21 '18 at 13:21
0

Looks like you are using anonymous inner class.

Here is the solution,

private class LoadData extends AsyncTask<Void, Void, String> {
    LoadData() {
    }

    @Override
    protected String doInBackground(Void... params) {
        return "task finished";
    }

    @Override
    protected void onPostExecute(String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Update your UI here
                //showProgressBar();
            }
        });
    }
}

 //Execute your task
 new LoadData().execute();
Chandrakanth M
  • 299
  • 1
  • 4
  • 10