0

当我尝试使用从 doInBackground 收到的值更新 SharedPreferences 时,AsyncTask onPostExecute 崩溃(报告 nullpointerexecption)。

我对调用活动的处理是:private DashboardActivity<?> callerActivity;没有<?>它抱怨。我尝试了几种方法:1)将 onPostExecute 中的 SP 更新为:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(callerActivity);
prefs.edit().putInt("lastrecord", intRec ).commit();

我还在 callerActivity 中调用了一个方法:

callerActivity.storeLastInsertedRecord(intRec);

所有错误都是相同的,这些行上的 nullpointerexecution。

我可能做错了什么?这个答案Android - 在 AsyncTask onPostExecute() 中设置的共享首选项并不总是设置?@denisdrew 是最接近的,但是当我尝试实例化意图时它在同一个地方崩溃:

Intent myIntent = new Intent(callerActivity.getApplicationContext(), SharedPrefsHelperActivity.class);

或者

Intent myIntent = new Intent(callerActivity.getBaseContext(), SharedPrefsHelperActivity.class);

我可能做错了什么?我知道我要推送的值不是 null (intRec)。

4

1 回答 1

0

所以问题很可能与分配给的 Context 有关NULL。我建议你通过 AsyncTask eq 的构造函数传递 Context 变量

private Context c;

public MyTask(Context c) {
   this.c = c;
}

并称它为:

new MyTask(YourCallerActivity.this).execute();


注意:我最近处理了类似的问题(在 onPostExecute 中保存 SharedPreferences)并且一切正常,因为我通过构造函数传递了 Context。

于 2013-04-06T19:54:27.943 回答