SharedPreferences makes app force close

∥☆過路亽.° 提交于 2019-12-12 03:46:04

问题


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 the app will remember the email.

my LoginActivity:

public class LoginActivity extends Activity
{
    private AppPreferences appPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);        
        appPreferences = new AppPreferences(); // this makes the app crash
        String email = appPreferences.getPreferenceString("email");
        // ...

the class appPreferences

public class AppPreferences extends Activity
{
    private SharedPreferences settings = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = this.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE);
    }
    public String getPreferenceString(String key) {
        return settings.getString(key, DEFAULT_STRING);
    }
    public void setPreferenceString(String key, String value) {
    editor.putString(key, (String) value);
    }
// ...

I've been looking for some hours to fix this and I tried several solutions from SO. I do call the getSharedPreferences method in the onCreate method so that wouldn't be the problem.

What am I doing wrong? I'm new to Java and Android developing so please describe fully with examples. Other solutions with a complete different approach are welcome too. Thanks in advance.


回答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 :

public class AppPreferences  
{
    private SharedPreferences settings = null;
    Context context;
    public AppPreferences(Context context){
     this.context=context;
     settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE);
    }
//your code here....

}

now pass Activity context using AppPreferences constructor as :

appPreferences = new AppPreferences(LoginActivity.this);
String email = appPreferences.getPreferenceString("email");



回答2:


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

Do like this way.

public class AppPreferences extends Activity
{
    private SharedPreferences settings = null;
    AppPreferences(Context context) {
        settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE);
    }

    ...//Rest of your code.

}

In Login activity.

appPreferences = new AppPreferences(this);


来源:https://stackoverflow.com/questions/15251942/sharedpreferences-makes-app-force-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!