0

I know how to save a list of Objects in Room database. But I really don't know how to save a list of primitive type i.e ArrayList<String> using Room. Any help is appreciated.

I know that I can have a class like this:

@Entity
public class MyData {
    @ColumnInfo(name = "data")
    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

And save the data using the conventional way. But I think there must be an easier way of saving simple data lists like ArrayList<String> using Room.

sajjad
  • 766
  • 4
  • 13
  • What do you mean by saving a list of strings? Just be more specific what do you want to do exactly – mmdreza baqalpour Oct 20 '20 at 06:36
  • 1
    The approach will be same . With room you can use `TypeConverter` .. [See this](https://stackoverflow.com/a/45477939/4168607). – ADM Oct 20 '20 at 06:39
  • So I concluded that it's not really easier to save `ArrayList` in a database. Same procedures! But a combination of the latter solution with `SharedPreferences`, I mean using `GSON` and `SharedPreferences` was pretty easy. Thanks @ADM – sajjad Oct 20 '20 at 06:56

1 Answers1

-1

So according to the suggestion from user ADM in the comments, I decided to use the solution at see this to convert my ArrayList to String and then save it using SharedPreferences. It seems this is the easiest way of persisting ArrayList<String>.

public static ArrayList<String> getPurchasedItems(Context context) {
    String listOfString = PreferenceManager.getDefaultSharedPreferences(context).getString("purchased_sku", "");
    return new Gson().fromJson(listOfString, new TypeToken<List<String>>() {}.getType());
}

public static void saveItems(Context context, ArrayList<String> purchasedItems) {
    PreferenceManager.getDefaultSharedPreferences(context)
            .edit().putString("purchased_sku", new Gson().toJson(purchasedItems)).apply();
}
sajjad
  • 766
  • 4
  • 13