[英]How to save a model with SharedPreferences?
I've got class to add some variables inside it.我有课程可以在其中添加一些变量。 I've created an object from it.
我从它创建了一个对象。 Then i've added some
value
to it.然后我为它增加了一些
value
。 The problem now is, i don't know how to add it inside.现在的问题是,我不知道如何在里面添加它。
SharedPreferences
i want to edit the code so i can add it without problems. SharedPreferences
我想编辑代码,以便我可以毫无问题地添加它。 // class : MainActivity // 类:主活动
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;
}
}
Just add editor.commit();只需添加 editor.commit(); delete editor.apply();
删除 editor.apply(); you can read explanation on shared prefs here https://www.tutorialspoint.com/android/android_shared_preferences.htm
您可以在此处阅读有关共享首选项的说明https://www.tutorialspoint.com/android/android_shared_preferences.htm
Ohad is correct.奥哈德是对的。 SharedPreferences only store primitive types like Int and String.
SharedPreferences 只存储原始类型,如 Int 和 String。 In this case you would have to store each value as its own SharedPreference.
在这种情况下,您必须将每个值存储为它自己的 SharedPreference。
If your data is more complex than what SharedPreferences can handle, consider storing it in a Room database.如果您的数据比 SharedPreferences 可以处理的更复杂,请考虑将其存储在Room数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.