Henri K.
Henri K.

Reputation: 3

Getting string from SharedPreferences in AsyncTask, java.lang.NullPointerException

I'm trying to get a string saved in SharedPreferences in AsyncTask, but unfortunately I get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Here's the relevant code:

public class FetchData extends AsyncTask<Void, Void, String> {

    private Context context;
    String deviceId;

    private AsyncInterface asyncInterface;

    public FetchData(AsyncInterface asyncInterface) {
        this.context = context;
        this.asyncInterface = asyncInterface;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        SharedPreferences sharedPreferences = context.getSharedPreferences("deviceId", MODE_PRIVATE); //Error here
        deviceId = sharedPreferences.getString("deviceId", deviceId);

    }
}

What did I do wrong ?

Upvotes: 0

Views: 44

Answers (1)

Christoph Nievergelt
Christoph Nievergelt

Reputation: 104

Maybe you should add a constructor parameter Context context.

Upvotes: 1

Related Questions