从AsyncTask的onPostExecute更新共享preferences [英] update shared preferences from AsyncTask onPostExecute
问题描述
AsyncTask的onPostExecute崩溃(报告nullpointerexecption),当我尝试使用我从doInBackground收到的值更新共享preferences。
AsyncTask onPostExecute crashes (reports nullpointerexecption) when I try to use the value I received from doInBackground to update SharedPreferences.
我的句柄调用活动是:<?code>私人DashboardActivity&LT;&GT; callerActivity; 用了&LT;&GT;
它抱怨。我已经特里几种方法:1)更新SP在onPostExecute为:
My handle to the calling activity is: private DashboardActivity<?> callerActivity;
with out the <?>
it complains. I've trie a couple of ways: 1) update SP in onPostExecute as:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(callerActivity);
prefs.edit().putInt("lastrecord", intRec ).commit();
我也叫了一个callerActivity方法:
I've also called a method in the callerActivity as:
callerActivity.storeLastInsertedRecord(intRec);
所有错误都一样,nullpointerexection这些线路上。
All the errors are the same, nullpointerexection on these lines.
什么可能我是做错了什么?这个答案<一个href=\"http://stackoverflow.com/questions/12604414/android-shared-$p$pferences-set-in-an-asynctask-onpostexecute-not-always-set\">Android ? - 共享preferences在AsyncTask的onPostExecute(套)并不总是通过设置的@denisdrew是最接近的,但它崩溃在同一个地方,当我尝试实例化意图:
What might I be doing wrong? This answer Android - shared preferences set in an AsyncTask onPostExecute() not always set? by @denisdrew is the closest, but for it crashes at the same place when I try instantiate the intent:
Intent myIntent = new Intent(callerActivity.getApplicationContext(), SharedPrefsHelperActivity.class);
或
Intent myIntent = new Intent(callerActivity.getBaseContext(), SharedPrefsHelperActivity.class);
什么可能被我做错了?我知道,我正在试图把值不为空(intRec)。
what might I be doing wrong? I know that the value that I'm trying to push is not null (intRec).
推荐答案
所以,问题最有可能涉及到分配给上下文的 NULL
。我建议你通过的AsyncTask如参见的构造函数传递上下文变量
So problem is most likely related to Context that is assigned to NULL
. I suggest you pass Context variable via constructor of AsyncTask e.q
private Context c;
public MyTask(Context c) {
this.c = c;
}
和调用它:
new MyTask(YourCallerActivity.this).execute();
结果
注意:我最近使用过类似的问题(节省共享preferences在onPostExecute)和一切运行良好,因为我可以通过构造通过上下文
Note: I recently worked on similar issue(saving SharedPreferences in onPostExecute) and everything worked fine since i passed Context via constructor.
这篇关于从AsyncTask的onPostExecute更新共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!