从AsyncTask onPostExecute更新共享首选项

时间:2013-04-06 19:50:55

标签: android android-asynctask sharedpreferences

当我尝试使用从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);

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

我可能做错了什么? @denisdrew的这个答案Android - shared preferences set in an AsyncTask onPostExecute() not always set?是最接近的,但是当我尝试实例化目标时它在同一个地方崩溃:

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

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

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

1 个答案:

答案 0 :(得分:0)

因此,问题很可能与分配给 NULL 的上下文有关。我建议你通过AsyncTask e.q

的构造函数传递Context变量
private Context c;

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

并称之为:

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


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

相关问题