我需要保存一些信息,我以前用的是sharedpreferences...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Data", (Data));
editor.commit();
所以我会做这样的事情来保存数据,但是对于这个项目,我使用的是 public class Tab3 extends View implements OnTouchListener
类型的类,我不确定这是否就是它不起作用的原因但它不是我不能使用 Shared Prefences onTouch 我在 getSharedPreferences
上收到错误消息说“方法 getSharedPreferences(String, int) 对于 Tab3 类型是未定义的”我需要做什么才能保存以某种方式获取这些数据,以便我以后可以在我的应用中使用它?
最佳答案
您需要上下文才能访问共享首选项。最好的方法是创建 MyApplication
作为 Application
类的后代,在那里实例化 preferences
并在您的应用程序的其余部分中使用它们作为 MyApplication.preferences
:
public class MyApplication extends Application {
public static SharedPreferences preferences;
@Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
例如,如果您需要在其他地方访问您的首选项,您可以调用它来读取首选项:
String str = MyApplication.preferences.getString( KEY, DEFAULT );
或者你可以调用它来保存一些东西到首选项:
MyApplication.preferences.edit().putString( KEY, VALUE ).commit();
(不要忘记在添加或更改首选项后调用 commit()
!)
关于java - 在 View 类中保存 sharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660692/