【发布时间】:2018-11-01 23:22:55
【问题描述】:
我有一个Activity,用户在上面注册,第二个Activity,到目前为止所有注册的用户,信息都会显示出来。
我知道这可以使用数据库轻松完成,但我想使用SharedPreferences。我正在使用 Gson 存储/检索数据。我有一个班级学生,字段为id(rollno),name。
我维护了一个用户数计数器,这个计数器将用于检索方。
将数据保存到共享首选项的代码:
SharedPreferences preferences =
getSharedPreferences("mypref",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor=preferences.edit();
Gson gson=new Gson();
if(preferences.contains("counter")){
counter=preferences.getInt("counter",0);
prefsEditor.putInt("counter",++counter);
}
else{
counter=0;
prefsEditor.putInt("counter",++counter);
}
String json = gson.toJson(student);
prefsEditor.putString("details"+counter,json);
prefsEditor.commit();
startActivity(intent);
}
获取SharedPreference的代码:
SharedPreferences mPrefs =
getSharedPreferences("mypref",MODE_PRIVATE);
int howMany=mPrefs.getInt("counter",0);
Gson gson = new Gson();
for(int i=1;i<=howMany;i++) {
String json = mPrefs.getString("details" + howMany, "");
Student student = gson.fromJson(json, Student.class);
Log.e("tag","loop number"+i);
Log.e("Tag", student.getName());
}
当应用程序启动时,我的第一个用户名是“Pra”,并且在第一个Activity 上单击了提交按钮,因此将其存储在SharedPreferences 中。
第二个用户的名字是“Suv”,这个值也存储在SharedPreferences中。现在的问题是第一个用户的名称的值也发生了变化。我不明白。
我维护了计数器,以便每个对象在 SharedPreferences 中都有唯一的条目,但日志显示:
05-23 10:45:48.208 18409-18409/com.example.com.applicationstudent
E/tag: counter: 2
05-23 10:45:48.212 18409-18409/com.example.com.applicationstudent
E/tag: loop number1
05-23 10:45:48.212 18409-18409/com.example.com.applicationstudent
E/Tag: suv
05-23 10:45:48.212 18409-18409/com.example.com.applicationstudent
E/tag: loop number2
05-23 10:45:48.212 18409-18409/com.example.com.applicationstudent
E/Tag: suv
再次,我不想使用数据库,我想使用SharedPreferences。
【问题讨论】:
-
String json = mPrefs.getString("details" + howMany, "");。那应该是String json = mPrefs.getString("details" + i, "");。 -
是的,我弄错了。非常感谢@greenapps
标签: android gson sharedpreferences android-sharedpreferences