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();
}
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.
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.
An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With