0

AsyncTask onPostExecute crashes (reports nullpointerexecption) when I try to use the value I received from doInBackground to update SharedPreferences.

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();

I've also called a method in the callerActivity as:

callerActivity.storeLastInsertedRecord(intRec);

All the errors are the same, nullpointerexection on these lines.

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);

or

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

what might I be doing wrong? I know that the value that I'm trying to push is not null (intRec).

Community
  • 1
  • 1
sAguinaga
  • 638
  • 13
  • 31
  • Why is DashboardActivity generic? – Raghav Sood Apr 06 '13 at 19:52
  • Partly because I don't know what I'm doing, and of the options suggested by Eclipse, I took that generic. Other AsyncTask classes that interact with my mysql over json don't complain when I leave it as `DashboardActivity callerActivity;` – sAguinaga Apr 07 '13 at 20:40

1 Answers1

0

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;
}

And call it like:

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


Note: I recently worked on similar issue(saving SharedPreferences in onPostExecute) and everything worked fine since i passed Context via constructor.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • Technically this suggestion works. Strictly speaking in this case it turns out that b/c callerActivity is actually of the form DashboardActivity, where spectrum refers to Surface view defined in the layout.xml. If I use the suggestion above, one of the things I'm trying to do is write to a remote db using my asynctask, so while it works, the data I write to the db does not get Inserted. – sAguinaga Apr 09 '13 at 06:48
  • So I had to abandon the suggestion for that reason. Elsewhere during a diff call to the remote server (in a diff. asynctask) I make fetch of the data that I want saved the shared preferences, and that works just fine b/c the callerActivity in this case is not of the ClassActivity>. – sAguinaga Apr 09 '13 at 06:49