本文介绍了如何将Context传递给AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Async Task
类中传递上下文,该类在主要活动
的不同java文件中编码但是它被调用来自主要活动?
How to pass context in Async Task
class which is coded in different java file from Main Activity
but it called from main activity?
以下是我的代码:
@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();
}
推荐答案
你可以传递一个 Context
实例作为构造函数参数(并保留 WeakReference
以避免内存泄漏)。
You could just pass a Context
instance as a constructor parameter (and keep a WeakReference
to it to avoid memory leaks).
例如:
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
}
}
}
执行:
new ExampleAsyncTask(aContextInstance).execute();
这篇关于如何将Context传递给AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!