【发布时间】:2019-09-04 16:47:50
【问题描述】:
要使用 JSON 在 Android Studio 上存储数组列表,它会转换为字符串,因此当检索到它时,我需要将其转换回数组列表。 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();
【问题讨论】:
标签: java android arrays json sharedpreferences