Save List of user-defined objects to SharedPreferences public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS"; SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
User entity = new User(); // ... set entity fields
List<Connection> connections = entity.getConnections(); // convert java object to JSON format, // and returned as JSON formatted string String connectionsJSONString = new Gson().toJson(connections); editor.putString(KEY_CONNECTIONS, connectionsJSONString); editor.commit(); Get List of user-defined objects from SharedPreferences String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null); Type type = new TypeToken < List < Connection >> () {}.getType(); List < Connection > connections = new Gson().fromJson(connectionsJSONString, type);
DİĞER
implementation 'com.google.code.gson:gson:2.8.8' you can find latest version here
Creating a shared preference:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); To save:
MyObject myObject = new MyObject; //set variables of 'myObject', etc.
Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(myObject); prefsEditor.putString("MyObject", json); prefsEditor.commit(); To retrieve: