Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Context to AsyncTask?

Tags:

How to pass context in Async Task class which is coded in different java file from Main Activity but it called from main activity?

Below is my code:

 @Override

protected void onPostExecute(List<Movie_ModelClass> result) {
        super.onPostExecute(result);

        if (result != null) {
            Movie_Adapter movieAdapter = new Movie_Adapter(new MainActivity().getApplicationContext() , R.layout.custom_row, result);
            MainActivity ovj_main = new MainActivity();
            ovj_main.lv_main.setAdapter(movieAdapter);
        } else {
            Toast.makeText(new MainActivity().getApplicationContext() ,"No Data Found", Toast.LENGTH_LONG);

        }
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
    }
like image 992
Darshan Dhoriya Avatar asked May 30 '16 18:05

Darshan Dhoriya


People also ask

Is AsyncTask deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

Is it possible to start AsyncTask from background thread?

Methods of AsyncTaskwe can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods . doInBackground(Params) − In this method we have to do background operation on background thread.

When AsyncTask is executed it goes through what steps?

An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.


1 Answers

You could just pass a Context instance as a constructor parameter (and keep a WeakReference to it to avoid memory leaks).

For example:

public class ExampleAsyncTask extends AsyncTask {
    private WeakReference<Context> contextRef;

    public ExampleAsyncTask(Context context) {
        contextRef = new WeakReference<>(context);
    }

    @Override
    protected Object doInBackground(Object[] params) {
        // ...
    }

    @Override
    protected void onPostExecute(Object result) {
        Context context = contextRef.get();
        if (context != null) {
            // do whatever you'd like with context
        }
    }
}

And the execution:

new ExampleAsyncTask(aContextInstance).execute();
like image 90
earthw0rmjim Avatar answered Oct 16 '22 11:10

earthw0rmjim