1

I simply want to store my mutable list/array list of Strings to SharedPreferences in order to retrieve the saved list again after re-opening the app (USING GSON).

!! WITHOUT using any class. It's a simple mutable list (I add things with usedCodesList.add("example")):

private var usedCodesList = mutableListOf<String>("022", "027")


I did not find any tutorial that fits what I need. (NO Class, NO Recycler View or List View or anything like that. I use usedCodesList.add(), usedCodesList.clear() and the Gson library ONLY)

Can someone help me? Any help is GREATLY appreciated!! I'm a beginner and almost dying

4
  • If the list is not going to have duplicates, I believe SP have option to save StringSet. Commented Oct 20, 2022 at 19:24
  • Okay. the list won't have duplicates. I heard StringSet before in the 2983 tutorials I watched. Can you explain it or link me a video? How do I do it? Commented Oct 20, 2022 at 19:26
  • A good practice is to share codes if possible, it is easy to reproduce problems. Commented Oct 20, 2022 at 19:57
  • Also sharing the code via images is often frowned upon, when someone is trying to help you, making them have to type the code is gonna make them very unlikely to help. (This case is fine, so far). Can you post more of the code? (Using the code formatting :-)) Commented Oct 20, 2022 at 20:33

1 Answer 1

2

It's pretty straightforward, just like any other type.

val editor = sharedPreferences.edit()
editor.putStringSet("my_list", usedCodesList.toSet())
editor.apply() // Note that editor should be used as atomical operation, not have it open all the time.

and

usedCodesList = sharedPrefences.getStringSet("my_list", emptySet())?.toMutableList() ?: mutableListOf()
Sign up to request clarification or add additional context in comments.

5 Comments

Oh my god, thank you, no errors!! I will try it out right now and update you!!
Okay, the app is running but there's a problem: I made the usedCodesList visible by setting a TextView. The TextView shows: "[]"... And my function to check if a code is in the list doesn't work now. Is the new, retrieved list null or something? And is the new retrieved list again like a mutable list (it should be right?) so can I access the codes like this: for (s in usedCodesList) { ?
Okay, sure. Well there are 2 Strings initially set in the list: "022" and "027". After pressing on my "Load List" button the list should appear. I wrote it like that: for (s in usedCodesList) { freeDrinkVoucherCaption.text = freeDrinkVoucherCaption.text.toString() + s.toString() }
Image updated!.
@MautendoSkill I am so sorry to bother you, but those too. It's maily for clarity if someone else would stumble on this question :-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.