【问题标题】:update shared preferences from AsyncTask onPostExecute从 AsyncTask onPostExecute 更新共享首选项
【发布时间】:2013-04-06 19:50:55
【问题描述】:

当我尝试使用从 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 就在这几行。

我可能做错了什么? @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)。

【问题讨论】:

  • 为什么 DashboardActivity 是通用的?
  • 部分是因为我不知道自己在做什么,并且在 Eclipse 建议的选项中,我采用了通用选项。当我将其保留为 DashboardActivity callerActivity; 时,其他通过 json 与我的 mysql 交互的 AsyncTask 类不会抱怨

标签: android android-asynctask sharedpreferences


【解决方案1】:

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

private Context c;

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

然后这样称呼它:

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


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

【讨论】:

  • 从技术上讲,这个建议是可行的。严格来说,在这种情况下,b/c callerActivity 实际上是 DashboardActivity 的形式,其中频谱指的是 layout.xml 中定义的 Surface 视图。如果我使用上面的建议,我想做的一件事是使用我的 asynctask 写入远程数据库,所以当它工作时,我写入数据库的数据不会被插入。
  • 因此我不得不放弃这个建议。在对远程服务器进行 diff 调用期间的其他地方(在 diff.asynctask 中),我获取了我想要保存共享首选项的数据,并且在这种情况下调用者活动不是 ClassActivity >.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2018-08-19
  • 2019-10-07
  • 2012-09-08
相关资源
最近更新 更多