【问题标题】:Turn arraylist from string into arraylist将arraylist从字符串转换为arraylist
【发布时间】: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


    【解决方案1】:

    你可以试试这样的

    List<String> yourList = new ArrayList<String>(Arrays.asList(yourString.split(",")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-28
      • 2012-08-29
      • 1970-01-01
      • 2015-07-22
      • 2014-09-19
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多