onPostExecute getResources().getString NullPointerException

4k Views Asked by At

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.

3

There are 3 best solutions below

1
On

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.

1
On

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

0
On

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