在我的应用程序中,我使用此类作为模型:
class ExpenseItem (val concept: String, val amount: String, val months: List<String>, val type: Type, val cards_image: Int, val payDay: Int, val notes: String) {
enum class Type {RECURRENT, VARIABLE}
}
使用这个模型,我创建了一个可变列表
var generalExpensesList: MutableList<ExpenseItem> = mutableListOf()
我添加项目
val currentExpense = ExpenseItem(
concept,
amount,
listOfMonths,
enumtype,
card_image_number,
payday.toInt(),
notes
)
generalExpensesList.add(currentExpense)
如您所见,在重要的情况下,模型字段之一也是String类型列表
好吧,我的意图是将该列表转换为String,将其另存为sharedpreference,然后使用从sharedpreference检索的String创建一个新列表。
要将列表转换为String,我可以使用toString或joinToString,两者都给我一个最佳结果。
我想从字符串创建新列表时遇到问题。
我可以使用
List<String>
类型的列表来做到这一点,但是永远不能使用List<ExpenseItem>
类型的列表来做到这一点有人可以帮我弄这个吗?
最佳答案
简单的方法,您可以使用Gson
库,将其添加到build.gradle,它将序列化您的列表为JSON
并将其保存到SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<ExpenseItem> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<ExpenseItem> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<ExpenseItem>>() {
}.getType();
List<ExpenseItem> result = new Gson().fromJson(json, type);
return result;
}
关于android - 使用Kotlin从另一个列表中提取的字符串创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62038580/