Android 保存列表<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11193983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:16:49  来源:igfitidea点击:

Android save List<String>

androidlistsave

提问by Luke Taylor

Is there anyway I can save a List variable to the Androids phone internal or external memory? I know I can save primitive data, yet not sure about this one.

无论如何我可以将 List 变量保存到 Androids 手机的内部或外部存储器中吗?我知道我可以保存原始数据,但不确定这个。

Thanks in advance.

提前致谢。

回答by Blundell

Yes exactly you can only save primitives so you could something like this:

是的,您只能保存原语,因此您可以这样做:

List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder csvList = new StringBuilder();
for(String s : list){
      csvList.append(s);
      csvList.append(",");
}

sharedPreferencesEditor.put("myList", csvList.toString());

Then to create your listagain you would:

然后再创建你的list,你会:

String csvList = sharedPreferences.getString("myList");
String[] items = csvList.split(",");
List<String> list = new ArrayList<String>();
for(int i=0; i < items.length; i++){
     list.add(items);     
}

You could encapsulate this "serializing" into your own class wrapping a list to keep it nice and tidy. Also you could look at converting your listto JSON.

您可以将此“序列化”封装到您自己的包含列表的类中,以使其保持整洁。您也可以考虑将您listJSON.

回答by Pir Fahim Shah

If you want to store/retrieve/delete some string value in your program, then Listis better than Array. Here below I will show you that how to use it.

如果你想在你的程序中存储/检索/删除一些字符串值,那么ListArray. 下面我将向您展示如何使用它。

 // Declaring List Variable
 List<String> Mylist = new ArrayList<String>();

 // Adding item to List
 Mylist.add(list.size(), "MyStringValue");   //this will add string at the next index

 // Removing element form list
 Mylist.remove(list.size()-1);   //this will remove the top most element from List