1

In my app, I need some data that I do not want to request every time from the server. This dat includes the userId and some array string. I think I can store the user id in the SharedPreferences, but what about the array?

Is it OK to use static variables?

fmw42
  • 46,825
  • 10
  • 62
  • 80
ROM
  • 153
  • 3
  • 16
  • updated the answer please check.. update if you got the answer .. – Santanu Sur Mar 02 '18 at 16:58
  • It's better to use some caching mechanism (Sqlite, ObjectBox, Realm, file, some ORM like Store.io, cache via http client) if you need to store array in prefs https://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences?rq=1 – Viktor Yakunin Mar 02 '18 at 16:58
  • You can store arraylist in shared preference https://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – tushar Mar 02 '18 at 16:59

3 Answers3

0

You can use Gson parse Array to String and save to shared preferences. When you read String from shared preferences you can use Gson to convert String to Array. Gson library

ArrayList<String> yourArrayStr = convertArrayToString(yourArray);
SharedPreferences prefs =  context.getSharedPreferences("PREFERENCE_NAME",
            Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("array_key_name", yourArrayStr);
editor.apply(); 

function: convertArrayToString

private String convertArrayToString(ArrayList<String> yourArray){
Gson gson = new Gson();
return gson.toJson(yourArray);
}

function convertStringToArray when you read String from shared preferences

private ArrayList<String> convertStringToArray(String yourArrayStr){
Gson gson = new Gson();
return gson.fromJson(yourArrayStr , new TypeToken<ArrayList<String>>(){}.getType());
}

Good luck!

nhonnq
  • 184
  • 1
  • 9
0

You also can serialize your array to save a array as string in preferences, but keep in mind that if it was big, use Sqllite...

Or you can use the firebase with offline function.

Donkaike
  • 496
  • 3
  • 5
0

First of all create a class model. like this

public class User implements Serializable {
@SerializedName("id")
private int id;

@SerializedName("array")
private ArrayList<String> array;

//your get/set are here too

}

I use gson to make my life easier.

Than on your server response save the Json on your SharedPreference

SharedPreferencesUtils.write(Constants.Preferences.Keys.USER_DATA, userJson);

And finally everytime you need to read this information you use

String json = SharedPreferencesUtils.read(Constants.Preferences.Keys.USER_DATA, null);
      User user = new Gson().fromJson(json, User.class);

I would load this information on your singleton to use everywhere i need it in the application :)

If you need to update it.. just get the response and save again on your SharedPreference.