在android应用程序中,我有列表视图,您可以在其中添加新对象,每个“对象”都有4-5个字符串值。我不认为任何人可以在应用程序中使用这些对象中的3或4个。
现在它是在数据库上创建的,SQLite,一个对象=一个记录,有4-5个值(输入文本),但是它越来越难维护,我认为它对应用程序的添加是迂回的。
这能通过共享的偏好来实现吗?或者存储这些数据不是个好主意?键和值如何,我可以在开始时概括它们吗?
发布于 2016-02-29 07:45:04
您将需要Gson将对象放入共享首选项中。您可以找到它这里,以及如何像这一样将它添加到您的项目中。不要忘记在gradle文件'build.gradle‘compile files ('libs/gson-2.2.4.jar')
中添加依赖项。
若要将对象放入共享首选项中,请使用以下命令:
SharedPreferences preferences = getSharedPreferences("name", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String serializedObj = gson.toJson(ObjectHere);
editor.putString("key", serializedObj);
editor.commit();
若要稍后检索数据,请执行以下操作
SharedPreferences preferences = getSharedPreferences("name", MODE_PRIVATE);
Gson gson = new Gson();
String serializedObj = preferences.getString("key", "DEFAULT");
ObjectType object = gson.fromJson(serializedObj, Object.class);
发布于 2016-02-29 07:11:38
您可以将数据写入文件,并在需要时使用文件名检索数据:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
如果您在后台线程(例如AsyncTask )中执行此任务,情况会更好。
发布于 2016-02-29 08:31:08
它可以用gson(https://github.com/google/gson)解决。只需在gradle依赖项部分添加compile files ('libs/gson-2.2.4.jar')
即可。
假设您使用class YOUR_CLASS
的Arraylist作为listview。即
private ArrayList<YOUR_CLASS> arraylist = new ArrayList<YOUR_CLASS>();
现在,在将item对象添加到您的arraylist
之后,您可以使用以下方法将其保存为共享首选项:
SharedPreferences preferences = getSharedPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String arraylist_in_string = gson.toJson(arraylist).toString(); //Converting it to String
editor.putString("YOUR_KEY", arraylist_in_string); //now saving the String
editor.commit();
现在,当您需要使用arraylist
时,可以使用
Gson gson = new Gson();
String arraylist_in_string = preferences.getString("YOUR_KEY", null);
if(arraylist_in_string != null) //if we have list saved
{
//creating a list of YOUR_CLASS from the string response
Type type = new TypeToken<ArrayList<YOUR_CLASS>>() {}.getType();
List<YOUR_CLASS> list = new Gson().fromJson(arraylist_in_string, type);
//now adding the list to your arraylist
if (list != null && list.size() > 0 )) {
arraylist.clear();// before clearing check if its not null.
arraylist.addAll(list);
}else //ie list isn't saved yet
{
//You may want to save the arraylist into Shared preference using previous method
}
https://stackoverflow.com/questions/35693693
复制相似问题