I have a JSON Array that I need to save. I was thinking about serializing it, but would it be better to just save it as a string in SharedPreferences and then rebuild it whe
Another Easy Way To Save JsonArray Into Sharedprefrences :
public void SaveFriendList(String key, JSONArray value) {
FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = FriendLst.edit();
editor.putString(key, value.toString());
editor.commit();
}
public String LoadFriendList() {
MyApplication.FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String FriendLsts = MyApplication.FriendLst.getString("Friends", "");
return FriendLsts;
}
Just Call this Code to get Your Json :-)
try {
JSONArray jarry1 = new JSONArray(LoadFriendList());
JSONObject jobject;
datamodelfriends.clear();
for (int i = 0; i < jarry1.length(); i++) {
jobject = jarry1.getJSONObject(i);
String FirstName = jobject.get("FirstName").toString();//You can get your own objects like this
datamodelfriends.add(new DataModelFriends(FirstName,...));
}
mAdapter = new CustomeAdapterFriendList(datamodelfriends, MainActivity.this);
RecyclerView_Friends.setAdapter(mAdapter);
} catch (Exception e) {
}
I have done the same thing ... serialize an objet to a json string and save it into shared prefs. No problem, but understand that ultimately the prefs are an XML file, so if you are reading / writing it a lot, it isn't going to perform well.
Here's a simple version using Kotlin to store a User class:
class PreferenceHelper(context: Context) {
companion object {
private const val prefsFileName = "com.example.prefs"
private const val userConst = "user"
}
private val prefs: SharedPreferences = context.getSharedPreferences(prefsFileName, MODE_PRIVATE)
var user: User?
get() = GsonBuilder().create().fromJson(prefs.getString(userConst, null), User::class.java)
set(value) = prefs.edit().putString(userConst, GsonBuilder().create().toJson(value)).apply()
}