[英]Android - Shared Preference with Two Classes
基本上,我想设置一个类,使其具有用于设备的getter和setter来存储和检索数据,以及用于访问它的其他类。 我设法使sharedpreferences在一个类中工作,但在两个类中遇到了麻烦(我熟悉Java但不熟悉Android,我读过某个地方,我不应该使用Activity,而是静态的,也不能正常工作)。 无论如何,这里是getter / setter类。
public class Storage extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
final SharedPreferences prefs = this.getSharedPreferences(
"uk.co.kenreid.examplestory", Context.MODE_PRIVATE);
String nameKey = "uk.co.kenreid.examplestory.name";
我在其他类中使用以下代码段进行访问(最终用作onclicklistener中的变量“ storage”):
final Storage storage = new Storage();
storage.storeItem("name", name);
System.out.println(storage.getString("name"));
尝试这个:
SharedPreferences prefs = this.getSharedPreferences("uk.co.kenreid.examplestory", Context.MODE_MULTI_PROCESS);
以共享首选项存储内容:
SharedPreferences prefs = getSharedPreferences("TOT", Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putString(key, value);
ed.commit();
您可以在onCreate方法中使用上面的代码。
从共享的偏好中获取一些东西:
SharedPreferences prefs = getSharedPreferences("TOT", Context.MODE_PRIVATE);
prefs.getString(key, null);
我相信您的问题是要从Activity
初始化SharedPreferences
吗?
假设这是您的问题,则可以通过Storage
类的构造函数传递一个Context
来初始化它。
例如。
SharedPreferences prefs;
public Storage(Context aContext){
prefs = aContext.getSharedPreferences("uk.co.kenreid.examplestory",
Context.MODE_PRIVATE);
}
然后通过原始的acessor方法进行访问。 最好是将Application Contex
t而不是Activity Context
传递给构造函数,因此在创建Storage类时,请在Activity中这样调用它:
Storage myStorage = new Storage(getApplicationContext());
同样,最好创建一个Singleton类,以允许您使用相同的Storage实例。 网上有很多Java单例教程。
尝试这样:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
mVariable = sharedPref.getBoolean(SettingsActivity.KEY_TO_VARIABLE, false);
检查getSharedPreferences的文档
在这里,第一个参数是存储数据的共享首选项的名称。 因此,您需要在每个类中使用相同的名称来访问相同的共享首选项。
您可以使用单独的类可以处理您的所有首选项
public class PreferenceManager {
public static void setLogInSuceess(boolean login, Context context) {
SharedPreferences preferences;
preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
preferences.edit().putBoolean("LOGIN", login).commit();
}
public static boolean getLogInSuceess(Context context){
SharedPreferences preferences;
preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean login = preferences.getBoolean("LOGIN", false);
return login;
}
}
随时随地使用它,
PreferenceManager.setLogInSuceess(true / false,context); boolean _login = PreferenceManager.getLogInSuceess(context);
尝试这个:
public class Storage extends Application
应用程序是用于共享活动数据的类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.