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 cannot 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