Create a list from a string extracted from another list with Kotlin Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Create a list from a string extracted from another list with Kotlin without wasting too much if your time.

The question is published on by Tutorial Guruji team.

In my application, I use this class as a model:

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}
}

And with this model, I create a mutable list

var generalExpensesList: MutableList<ExpenseItem> = mutableListOf()

and I add items

 val currentExpense = ExpenseItem(
                    concept,
                    amount,
                    listOfMonths,
                    enumtype,
                    card_image_number,
                    payday.toInt(),
                    notes
                )

                generalExpensesList.add(currentExpense)

As you can see, one of the model fields is also a String type list, in case it was important

Well, my intention is to convert this list to String, save it as a sharedpreference, and then create a new list using that String retrieved from the sharedpreference. To convert the list to String I can use toString or joinToString, both give me an optimal result. I have the problem when I want to create a new list from the String. I can do it with lists of type List<String>, but never with lists of type List<ExpenseItem>

Can someone help me with this?

Answer

Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to 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;
    }
We are here to answer your question about Create a list from a string extracted from another list with Kotlin - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji