[英]Saving sharedPreferences in a View class
我需要保存一些信息,我過去使用的是共享偏好...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Data", (Data));
editor.commit();
所以我會做這樣的事情來保存數據,但是對於這個項目,我使用public class Tab3 extends View implements OnTouchListener
類的類型,我不知道這是不是為什么這不起作用,但它不是我不能使用共享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()
!)
我會做lenik所說的但是不要讓它們變得靜止,懶惰的是它們。
public class MyApplication extends Application {
public SharedPreferences preferences;
public SharedPreferences getSharedPrefs(){
if(preferences == null){
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
}
return preferences;
}
然后在你看來:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
正如eric所說,需要在清單中聲明此Application類:
<application android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
參考:
編輯
(從你的評論中)問題是你實際上沒有保存任何數據,這條線沒有意義你實際上沒有保存變量:
editor.putString("Data", (Data));
以下是使用中的上述示例:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
String str = settings.getString("YourKey", null);
並保存一些優惠:
settings.edit().putString("YourKey", "valueToSave").commit();
在自定義視圖中使用的更具體示例是:
public class MyView extends View {
SharedPreferences settings;
// Other constructors that you may use also need the init() method
public MyView(Context context){
super(context);
init();
}
private void init(){
MyApplication app = (MyApplication) getContext().getApplicationContext();
settings = app.getSharedPrefs();
}
private void someMethod(){ // or onTouch() etc
settings.edit().putString("YourKey", "valueToSave").commit(); //Save your data
}
private void someOtherMethod(){
String str = settings.getString("YourKey", null); //Retrieve your data
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.