3

I have an array, and want to store it in SharedPreferences but when I try, it doesn't get saved. Here is the code:

editor.putInt("Symptoms Checklist Baseline Matrix", symptoms_checklist_arr_base);

Where I have made

int symptoms_checklist_arr_base[] = new int[20];

In later code, I try to retrieve this value.

int symptoms_checklist_arr_base[] = prefs.getInt("Symptoms Checklist Baseline Matrix", what do I add as a default?? );

What would I need to do in order to get SharedPreferences to store arrays and return them?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
sjgandhi2312
  • 155
  • 1
  • 2
  • 10
  • 2
    `putInt` puts a single integer, not an array... – OneCricketeer Feb 29 '16 at 19:33
  • Sorry, I will edit those parentheses out, they were from some experimenting. I am wondering what I should replace putInt with. – sjgandhi2312 Feb 29 '16 at 19:34
  • 1
    Reading the documentation, you can only put single key-values. Where those values are primitives, not objects. If you want complex data, you'll need to serialize it into a String like JSON or something – OneCricketeer Feb 29 '16 at 19:36
  • Okay. For now, I will just put the individual values into shared preferences and just work with that unless another answer has a better solution. Thanks – sjgandhi2312 Feb 29 '16 at 19:39
  • 1
    It is possible to store an array, you just have to save it to a string, then parse it out later. If you are open to using Gson, I can provide an answer – OneCricketeer Feb 29 '16 at 19:40
  • I think it will be too complex for me. This is my first android project, so I will try to just get a functioning app before trying to use new APIs. Thank you for the offer though. – sjgandhi2312 Feb 29 '16 at 19:44
  • I'll toss something together for you to just look at, then. Maybe someone else will find it useful – OneCricketeer Feb 29 '16 at 19:50

1 Answers1

0

You can either convert the Array into List and then store that as a String using ObjectSerializer or put the List itself into a Parcelable object.

Refer this question, for implementation using ObjectSerializer: Save ArrayList to SharedPreferences

Refer this question, for implementation using Parcelable: Pass ArrayList<? implements Parcelable> to Activity

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Abdul Rahman K
  • 664
  • 5
  • 16