Skip to content

Instantly share code, notes, and snippets.

@Binary-Finery
Last active December 22, 2017 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Binary-Finery/c16288768e9fb83a291a8cca2b6f4975 to your computer and use it in GitHub Desktop.
Save Binary-Finery/c16288768e9fb83a291a8cca2b6f4975 to your computer and use it in GitHub Desktop.
store/retrieve array list of objects from/to shared preferences example
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
class PrefsUtils {
private static final String DATA_BASE_RECORDS = "db records", DEFAULT = "";
static List<Person> allRecords(Context context) {
List<Person> temp;
SharedPreferences db = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String content = db.getString(DATA_BASE_RECORDS, DEFAULT);
if (content.isEmpty()) {
temp = new ArrayList<>();
} else {
Type type = new TypeToken<List<Person>>() {
}.getType();
temp = gson.fromJson(content, type);
}
return temp;
}
static void addRecord(Context context, String... s){
List<Person> temp = allRecords(context);
SharedPreferences db = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = db.edit();
temp.add(new Person(s[0], s[1], s[2]));
Gson gson = new Gson();
String dbs = gson.toJson(temp);
editor.putString(DATA_BASE_RECORDS, dbs).apply();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment