Skip to content Skip to sidebar Skip to footer

Sharedpreferences Makes App Force Close

I want to read and write SharedPreferences through a class, but when I call this class in my Activity it makes the app crash/force close If the CheckBox 'Remember email' is checked

Solution 1:

because you are trying to create an object of class which extending Activity class. if AppPreferences is non Activity class then just pass current Activity context for separating SharedPreferences related code in separate java class as :

publicclassAppPreferences  
{
    privateSharedPreferencessettings=null;
    Context context;
    publicAppPreferences(Context context){
     this.context=context;
     settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE);
    }
//your code here....

}

now pass Activity context using AppPreferences constructor as :

appPreferences = newAppPreferences(LoginActivity.this);
Stringemail= appPreferences.getPreferenceString("email");

Solution 2:

Do not extend Activity class in AppPreferences. and remove the onCreate() method.

Do like this way.

publicclassAppPreferencesextendsActivity
{
    privateSharedPreferencessettings=null;
    AppPreferences(Context context) {
        settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE);
    }

    ...//Rest of your code.

}

In Login activity.

appPreferences = new AppPreferences(this);

Post a Comment for "Sharedpreferences Makes App Force Close"