I have a fragment and I want to call to a method which is in a AppConfig.class. But when I run the application there was a error came as " Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference"
. How do I solve this error?
Here is my code in AppConfig.class
public void updateUserLoginStatus(boolean status){
SharedPreferences.Editor editor= sharedPreferences.edit();
editor.putBoolean(context.getString(R.string.pref_is_user_login),status);
editor.apply();
}
Here is my code in Fragment
appConfig.updateUserLoginStatus(false);
2
Answers
You need to create a Appconfig object in your calling Activity/fragment.
Example –
Appconfig appconfig = new Appconfig ();
appconfig.updateUserLoginStatus(false);
Null pointer exception shows that, you have just declared a global variable in your class for appConfig but not initialised it.
If you want to access Shared Preference as default file name from all activities/fragment then consider to use
So in
AppConfig
class you can implement a void where you can passContext
from different Activities to getgetDefaultSharedPreferences
.Before call
updateUserLoginStatus
, you have to callAppConfig.init()
.From Activity –
From Fragment –