Last active
December 22, 2017 13:54
-
-
Save Binary-Finery/c16288768e9fb83a291a8cca2b6f4975 to your computer and use it in GitHub Desktop.
store/retrieve array list of objects from/to shared preferences example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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