问题
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