我有一个异步任务,其中有一个警告,它应该是静态的,否则可能会发生泄漏。
所以我用了这样一个弱引用:
private static class GetContacts extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;
GetContacts(Novinky context) {
activityReference = new WeakReference<>(context);
}
@Override
protected void onPreExecute() {
// get a reference to the activity if it is still there
Novinky activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
super.onPreExecute();
dialog = new ProgressDialog(activity);
dialog.setMessage("NaÄÃtavam");
dialog.setTitle("Pripájam sa k serveru");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... args) {
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");
for (int i = 0; i < actors.length(); i++) {
JSONObject c = actors.getJSONObject(i);
Actors actor = new Actors();
actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));
actorsList.add(actor);
}
} catch (final JSONException e) {
Novinky.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); }
return true;
} else {
Novinky.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();
}
});
return false;
}
}
protected void onPostExecute(Boolean result) {
// get a reference to the activity if it is still there
Novinky activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
super.onPostExecute(result);
dialog.dismiss();
adapter.notifyDataSetChanged();
}
}
1/
actorsList.add(actor);
-在我的for循环中现在说
无法从静态上下文引用非静态字段“actorsList”
2/
Novinky.this.runOnUiThread
-
无法从静态上下文引用
Novinky activity = activityReference.get();
activity.runOnUiThread
然后发出警告
此字段泄漏上下文对象
3/
adapter.notifyDataSetChanged();
. 错误显示:
无法从静态上下文引用非静态字段“适配器”
更新:我以某种方式解决了它,现在我没有错误,应用程序正在运行,但仍然不确定我是否正确解决了它:
对于定义的1/I
static ArrayList<Actors> actorsList;
2/在捕获中,否则我定义
final Novinky activity = activityReference.get();
然后:
3/在我使用的onPostExecute中
activity.adapter.notifyDataSetChanged();