Richard McKenna Richard McKenna - 4 days ago 5
Android Question

SharedPreferences in non activity class NullPointerException

I'm trying to use

SharedPreferences
in a non activity class from
onResume()
in an activity but I'm getting a NullPointerException on the context.

For some reason I can't get the context in
onResume()
. Not sure if I'm missing something, but any help would be appreciated.

onResume() Method in my activity

@Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").

// Check User's Access Token exists and hasn't expired.
AccountFunctions accountFunctions = new AccountFunctions();

if (!accountFunctions.validateUserToken(this)) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}


validateUserToken(Context context) method in AccountFunctions Class

public Boolean validateUserToken(Context context) {

SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(getString(R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(getString(R.string.user_expires), 0));

if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}


The Error

java.lang.RuntimeException: Unable to resume activity {uk.co.itsstonbury.www.intouch/uk.co.itsstonbury.www.intouch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Answer

replace getString(R.str with context.getString because AccountFunctions class has not been created by the OS so it doesn't have it's own context ready.

Basically activity gets it's context form application when oncreate function get called by OS callbacks since it's not gonna happen in this case so AccountFunctions object will not have it's own context

This code simply assume that AccountFunctions will be created normally through intent but in this case it is like a simple class object which has no connection with activity life-cycle calls.

so your code will look like

public Boolean validateUserToken(Context context) {

    SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
    String accessToken = sharedPref.getString(context.getString(R.string.user_access_token), null);
    DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));

    if (accessToken == null || expiryDate.isBeforeNow()) {
        return false;
    } else {
        return true;
    }
}

or you can use string values directly

    SharedPreferences sharedPref = context.getSharedPreferences("yourkey", Context.MODE_PRIVATE); // This is where the error is thrown

or

The better option is create a separate Util class for helper function rather like

class Util{

    public static boolean validateUserToken(Context context) {

        SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
        String accessToken = sharedPref.getString(context.getString(context.R.string.user_access_token), null);
        DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));

        if (accessToken == null || expiryDate.isBeforeNow()) {
            return false;
        } else {
            return true;
        }
    }
}

from your activity call it like

 Util.validateUserToken(this,1212);
Comments