共享preferences使应用程序强制关闭 [英] SharedPreferences makes app force close
问题描述
我要读取和写入共享preferences
通过类,但是当我在我的活动调用这个类它使应用程序崩溃/强制关闭
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.
我的 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");
// ...
类应用preferences
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);
}
// ...
我一直在寻找一些时间来解决这个问题,我从这么试了几种解决方案。我称之为 getShared preferences
方法在的onCreate
方法,这样就不会成为问题。
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.
我是什么做错了吗?我是新来的Java和Android发展得如此充分,请举例说明。一个完整的不同的方法,其他的解决方案也欢迎。先谢谢了。
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.
推荐答案
由于您要创建一个扩展Activity类类的一个对象。如果应用程序preferences非活动类,那么只传递当前活动上下文相关的分离code在单独的Java类的共享preferences:
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....
}
现在通过使用应用preferences
构造为活动背景:
now pass Activity context using AppPreferences
constructor as :
appPreferences = new AppPreferences(LoginActivity.this);
String email = appPreferences.getPreferenceString("email");
这篇关于共享preferences使应用程序强制关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!