I want to save a list of strings to a SharedPreferences object. I use these methods but if a set is (2,1,3) when I read it the list is (1,2,3). I don't want to sort the set when I read the array.
EDIT: When I use getSharedPreferences the set is already sorted inside the sharedPreferences object.
private List<String> load() {
Set<String> values = sharedPreferences.getStringSet(PREF_KEY, null);
return new ArrayList<String>(values);
}
private void save(List<String> values) {
//values = (2,1,3)
Set<String> valuesSet = new HashSet<String>(values);
//valuesSet = (1,2,3)
sharedPreferences.edit()
.putStringSet(PREF_KEY, valuesSet).commit();
}
Use serialisation:
private void save(List<String> values) {
String serialisedString = ObjectSerializer.serialize(values);
sharedPreferences.edit()
.putString(PREF_KEY, serialisedString).commit();
}
private List<String> load() {
String serialisedString = sharedPreferences.getString(PREF_KEY, ObjectSerializer.serialize(new ArrayList<String>()));
ArrayList<String> retrievedValues = (ArrayList<String>) ObjectSerializer.deserialize();
return retrievedValues;
}
Related
I would like to restore the state of my array after a change of orientation. But I don't see an aproprieted function for this case. What shoul I do?
public class PuzzlePiece extends android.support.v7.widget.AppCompatImageView {
public int xCoord;
public int yCoord;
public int pieceWidth;
public int pieceHeight;
public boolean canMove = true;
public PuzzlePiece(Context context) {
super(context);
}
This is my onSave method
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArray("image", pieces);
}
}
And data initalization:
ArrayList<PuzzlePiece> pieces;
Basically speaking, you need to implement two methods: saveData() and loadData(). These will use GSON library in order to transform any object into a string and then re-create them back. Then you save and restore your objects where ever you need. You may do so when onPause() method is called, or anywhere else.
Here is the code:
Firstly, add the following dependency line in your build.gradle:
implementation 'com.google.code.gson:gson:2.8.6'
Then you write those two methods
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arraylistOfYourObjects);
editor.putString("data_id", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("data_id", null);
Type type = new TypeToken<ArrayList<YourObjectClass>>() {}.getType();
arraylistOfYourObjects = gson.fromJson(json, type);
if(arraylistOfYourObjects == null){
arraylistOfYourObjects = new ArrayList<>();
}
}
Here is a link to a complete video on how to do the whole thing with allthe details:
https://www.youtube.com/watch?v=jcliHGR3CHo
I want to save this array list data in sharedpreferences and access that data in another fragment .Please Give me suggestion
Array list content given bellow
public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;
Here is solution,
Step 1: Create a class like
SharedPreference
public static final String FAVORITES = "PRODUCTS";
private SharedPreferences settings;
private Editor editor;
public SharedPreference() {
super();
}
Now code to save ArrayList
public void saveArrayList(Context context, List<String> unread_ids) {
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(unread_ids);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
Now code to get saved Arraylist
public ArrayList<String> getSavedList(Context context) {
// SharedPreferences settings;
List<String> unReadId;
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, "");
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites,
String[].class);
unReadId = Arrays.asList(favoriteItems);
unReadId = new ArrayList<>(unReadId);
} else {
return new ArrayList<String>();
}
return (ArrayList<String>) unReadId;
}
Code to save list:
sharedPreferences.saveArrayList(context, <YOUR LIST NAME>);
Now code to get your Arraylist in other Fragment
<LIST NAME> = sharedPreference.getSavedList(getActivity());
Before get and save array list you have to declare "sharedPreference" and create its object.
Hope this will help you.
I did something similar to this before Please check this code
private List<String> list; /// adding checked items to list
inside your OnCreate() add this line
list = new ArrayList<>(); /// checked items list
and to get array from model and store it local please use next.
int searchListLength = items.size();
for (int i = 0; i < searchListLength; i++) {
if (items.get(i).isChecked()) {
items.get(i).getId();
Log.d("listitem", String.valueOf("id=" + items.get(i).getId()));
list.add("id=" + items.get(i).getId());
}
}
StringBuilder stringBuilder = new StringBuilder();
for (String s : list) {
stringBuilder.append(s);
stringBuilder.append("&");
}
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_notaif = notif_array.edit();
editor_notaif.putString("id", stringBuilder.toString());
editor_notaif.apply();
Intent intent = new Intent(MainActivity.this, Filtered_Activity.class);
startActivity(intent);
Inside your another activity / fragment
private String new_result;
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
new_result = notif_array.getString("id", null);
/// i have tried to make an weather app, its fully functional, however, i have implemented the code and the data does save as there are no errors in the logcat, however, when i look in the bookmarked activity the saved weather location is not there. is there that any can help me
public class SaveData {
private static final String TAG ="SaveData";
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
private static String prefName = "Pref";
public static ArrayList<HistoryObj> weatherHistoryList = new ArrayList<>();
//KEYS to store
public static String WEATHER_LIST_KEY= "WeatherIds";
public SaveData(Context context){
int PRIVATE_MODE = 0;
this.context = context;
preferences = context.getSharedPreferences(prefName,PRIVATE_MODE);
editor = preferences.edit();
// TinyDb is class to simplify storage of ArrayList in Shared Preferences
// getting book marked list from storage
weatherHistoryList = getWeatherList();
}
public ArrayList<HistoryObj> getWeatherList(){
Gson gson = new Gson();
ArrayList<String> objStrings = getListString(WEATHER_LIST_KEY);
ArrayList<HistoryObj> objects = new ArrayList<HistoryObj>();
for(String jObjString : objStrings){
HistoryObj value = gson.fromJson(jObjString, HistoryObj.class);
objects.add(value);
}
return objects;
}
public void saveWeatherList(ArrayList<HistoryObj> objArray){
checkForNullKey(WEATHER_LIST_KEY);
Gson gson = new Gson();
ArrayList<String> objStrings = new ArrayList<String>();
for(HistoryObj obj : objArray){
objStrings.add(gson.toJson(obj));
}
putListString(WEATHER_LIST_KEY, objStrings);
}
public ArrayList<String> getListString(String key) {
return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}
public void putListString(String key, ArrayList<String> stringList) {
checkForNullKey(key);
String[] myStringList = stringList.toArray(new String[stringList.size()]);
preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}
}
I want to save and read List<MyObj> to sharedPreferences using Gson.
This is my write method:
private static final String GAS_STATIONS_LIST_KEY = "gasStationsListKey";
#Override
public void save(#NonNull List<MyObj> gasStations) {
saveStr(GAS_STATIONS_LIST_KEY, gson.toJson(gasStations));
}
private void saveStr(#NonNull String key, #Nullable String value) {
sharedPreferences
.edit()
.putString(key, value)
.apply();
}
And this is my read method:
#Override
public List<MyObj> getGasStationList() {
final Type type = new TypeToken<List<MyObj>>() {
}.getClass();
final List<MyObj> gasStations = gson.fromJson(GAS_STATIONS_LIST_KEY, type); // here null
if (gasStations != null && !gasStations.isEmpty()) {
return gasStations;
} else {
return new ArrayList<>();
}
}
But when I try read data I get null (comment in last code part).
How to fix it?
You are not getting the saved json content from shared prefences. You are trying to deserialize the key to a list, not the json content which is saved with that key.
Change this:
final List<MyObj> gasStations = gson.fromJson(GAS_STATIONS_LIST_KEY, type);
To this:
String savedJsonContent = sharedPreferences.getString(GAS_STATIONS_LIST_KEY, null);
final List<MyObj> gasStations = gson.fromJson(savedJsonContent , type);
SharedPreferences only store primitive data Types.
I have a bundle passed from one activity to another. That contains String n (the length is max 30), String ID and String color. I need to save these values to an ArrayList as an array (n, ID, color) and then to save ArrayList to androids memory. I was looking for a best way of doing that.. I've tried database but its to complicated for me at the moment and I don't think I need such a complex thing. I've tried FileOutputStream (as it explained here: http://developer.android.com/guide/topics/data/data-storage.html#pref?) but it's not working for me, probably because I'm doing something wrong. Do I actually need to create an arraylist of arrays or may be i could use arraylist of bundles, or any other way..? Whats the best way...? Please help..
Thanks every one...Was trying all this time but no luck.. I'm posting the code hoping that someone could give me a hand on that:
public class MainActivity extends Activity
{
String gotNotes;
String n;
String gotDOW;
String gotID;
public String clrs;
public String id;
public String nts;
String gotHour;
String gotColor;
TextView notes;
public static String FILENAME = "allevents";
String[] newevent;
String[] events;
SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button settings = (Button)findViewById(R.id.settings);
Bundle gotPackage = getIntent().getExtras();
if (gotPackage != null){
gotNotes = gotPackage.getString("AddedNote");
if (gotNotes.equals(" "))
{
n = "Empty";
}
else
{
n = gotNotes;
}
//gotDOW = gotPackage.getString("Day");
//gotHour = gotPackage.getInt("Hour");
gotID = gotPackage.getString("ID");
gotColor = gotPackage.getString("color");
initialize();
}
else{}
settings.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(v.getContext(),Settings.class);
startActivityForResult(i,0);
}
});
}
private void initialize()
{
// TODO Auto-generated method stub
String[] newevent = {n, gotID, gotColor};
ArrayList<String[]> events = new ArrayList<String[]>();
events.add(newevent);
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", events.toString());
editor.commit();
String allData = sharedPref.getString("yourKey", null);
String[] playlists = allData.split(",");
/* for (int number=0;number<events.lastIndexOf(sharedPref);number++)
{
notes = (TextView)findViewById(getResources().getIdentifier(playlists[number], getString(0), allData));
notes.setText(number+1);
}*/
notes = (TextView)findViewById(getResources().getIdentifier(gotID, "id",getPackageName()));
notes.setText(n);
notes.setGravity(Gravity.CENTER_HORIZONTAL);
notes.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
if (gotColor.equals("Blue")){
notes.setBackgroundColor(Color.rgb(99, 184, 255));}else
if(gotColor.equals("Green")){
notes.setBackgroundColor(Color.rgb(189, 252, 201));}else
if(gotColor.equals("Yellow")){
notes.setBackgroundColor(Color.rgb(238, 233, 191));}else
if(gotColor.equals("Grey")){
notes.setBackgroundColor(Color.LTGRAY);}else
if(gotColor.equals("Aqua")){
notes.setBackgroundColor(Color.rgb(151, 255, 255));}else
if(gotColor.equals("White")){}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Simply use SharedPreferences to save your application's data.
SharedPreferences sharedPref = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = activity.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", yourArray.toString());
editor.commit();
To get your array as String do the following:
String arrayString = sharedPref.getString("yourKey", null);
You can save array into shared preferences and retrieve it back. Here is a good example with fully functional code.