android - 使用Kotlin从另一个列表中提取的字符串创建列表

标签 android kotlin collections sharedpreferences

在我的应用程序中,我使用此类作为模型:

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/

相关文章:

java - 如何在每次滑动时显示各种布局

android - FileDescriptor在Android中的实际系统文件描述符(作为int)

Android HttpUrlConnection 执行 POST 而不是 GET

inheritance - Kotlin界面实现打破了 `equals`覆盖

Java编程,解决时遇到死循环。提供了问题的图像链接和代码。

c# - 我能有一本按日期排序的字典吗

algorithm - 根据嵌套类型过滤对象列表

android - Google Play 游戏服务 - 未登录下一个 Activity

android - 选择字符串中的前 X 位数字并将每个数字替换为 Character

kotlin - 嵌套的安全通话Null Check Kotlin