要使用JSON在Android Studio上存储arraylist,它会变成一个字符串,因此在检索它时我需要将其转换回arraylist。 arraylist包含对象。或者有没有办法将具有共享首选项的arraylists存储为arraylist而不是字符串。
SharedPreferences accountReader = getSharedPreferences("storedAccounts",MODE_PRIVATE);
SharedPreferences.Editor accountEditor = getSharedPreferences("storedAccounts",0).edit();
ArrayList<userAccount> accountsList = new ArrayList<userAccount>();
Gson gson = new Gson();
String json = accountReader.getString("accounts","");
if(json.isEmpty() == false){
//repopulate accountsList with the stored values
}
userAccount newEntry = new userAccount();
newEntry.id = id;
newEntry.username = username;
newEntry.password = password;
newEntry.url = url;
newEntry.note = note;
accountsList.add(newEntry);
Gson gsonTwo = new Gson();
String jsonTwo = gsonTwo.toJson(accountsList);
accountEditor.putString("accounts",jsonTwo);
accountEditor.apply();
accountEditor.commit();
你可以尝试这样的事情
List<String> yourList = new ArrayList<String>(Arrays.asList(yourString.split(",")))