2

When I run below code in the onPostExecute, it gives me an exception: java.lang.NullPointerException

getApplicationContext().getResources().getString(R.string.lbl_sth);
getBaseContext().getResources().getString(R.string.lbl_sth);

R.string.lbl_sth is definitely correct. If I run above two lines in onCreate, both lines work as expected.

Gunnar Bernstein
  • 6,074
  • 2
  • 45
  • 67
fordiy
  • 264
  • 5
  • 10

3 Answers3

3

Don't use getBaseContext() in your AsyncTask... pass your Activity as a context to the AsyncTask instead. Then call getResources().getString(...) on the Activity directly.

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • 2
    NOT work. Inside the onPostExecute I call a UI's method, in that method I try to getString(R.string.lbl_sth). But no luck with any solution. Activity already there, still java.lang.NullPointerException. – fordiy Aug 05 '12 at 06:32
0

You should pass the Strings from the Resources in the constructor of the AsyncTask:

public MyAsyncTask(String lblString) {
    this.lblString = lblString; 
}

you would construct and execute your task like this from an Activity/Fragment:

new MyAsyncTask(getString(R.string.lbl_sth)).execute();
donfuxx
  • 11,277
  • 6
  • 44
  • 76
-2

Try to use getActivity().getResources().getString(R.string.lbl_sth);

vovan888
  • 748
  • 6
  • 10