skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. If you want to access Shared Preference as default file name from all activities/fragment then consider to use

    getDefaultSharedPreferences(Context context)

    Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

    So in AppConfig class you can implement a void where you can pass Context from different Activities to get getDefaultSharedPreferences .

    private static Context context;
    static SharedPreferences sharedPreferences;
    
    public static void init(Context ctx){
        context = ctx;
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    
    }
    

    Before call updateUserLoginStatus , you have to call AppConfig.init() .

    From Activity –

         AppConfig.init(this);
    
        AppConfig appConfig = new AppConfig();
        appConfig.updateUserLoginStatus(false); 
    

    From Fragment –

         AppConfig.init(getContext());
         AppConfig appConfig = new AppConfig();
         appConfig.updateUserLoginStatus(false);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search