[英]How to save a model with SharedPreferences?
我有課程可以在其中添加一些變量。 我從它創建了一個對象。 然后我為它增加了一些value
。 現在的問題是,我不知道如何在里面添加它。 SharedPreferences
我想編輯代碼,以便我可以毫無問題地添加它。 // 類:主活動
public class MainActivity extends AppCompatActivity {
Times times;
public static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = context;
times = new Times(5,30);
// setInt(times);
}
public final static String PREFS_NAME = "appname_prefs";
public static void setInt(String key, int value) {
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME ,0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
return prefs.getInt(key , 0);
}
}
// class Times:
public class Times{
int Houre;
int Minute;
public Times(int houre, int minute){
Houre = houre;
Minute = minute;
}
public void setHoure(int houre){
Houre = houre;
}
public void setMinute(int minute){
Minute = minute;
}
public int getHoure(){
return Houre;
}
public int getMinute(){
return Minute;
}
}
只需添加 editor.commit(); 刪除 editor.apply(); 您可以在此處閱讀有關共享首選項的說明https://www.tutorialspoint.com/android/android_shared_preferences.htm
奧哈德是對的。 SharedPreferences 只存儲原始類型,如 Int 和 String。 在這種情況下,您必須將每個值存儲為它自己的 SharedPreference。
如果您的數據比 SharedPreferences 可以處理的更復雜,請考慮將其存儲在Room數據庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.