This question already has an answer here:
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
replace
getString(R.str
withcontext.getString
becauseAccountFunctions
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 soAccountFunctions
object will not have it's own contextThis code simply assume that
AccountFunctions
will be created normally throughintent
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
or you can use string values directly
or
The better option is create a separate Util class for helper function rather like
from your activity call it like
Replace
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE);
withSharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE);