Shared Preferences for Arraylist - android

I've a bunch of strings in an arraylist.
I want to save some of the strings in a shared preferences.
like if user selects a sting whose index is 3, I want to store that particular string in a shared preference.
Is it possible?
Please let me know.

I hope that this code will help you understand it
int id = selectedItemNum;
ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
list.add("Item2");
list.add("Item3");
list.add("Item4");
String selectedString = list.get(id);
String APP_PREFERENCES = "savedStrings";
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = mySharedPreferences.edit();
editor.putString("savedString"+id, selectedString);
editor.apply();

To save data to SharedPreferences:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
for(int i=0; i<arraylist.size(); i++){
sharedPreferences.edit().putString("TAG" + Integer.toString(i)
,arraylist.get(i)).apply();
}
To get data from SharedPreferences:
sharedPreferences.getString("TAG" + "x", null); x is a number position in array list

Related

How can I add elements inside HashMap and save it? [Android]

I'm new with HashMap, how can I save permanently and add other items when I reopen the application?
For example:
private HashMap<String, Recognition> registered = new HashMap<>();
public void register(String name, Recognition rec) {
registered.put(name, rec);
}
I can see all items inside registered using:
for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
final String name = entry.getKey();
... }
But when I close and reopen app, I can't see all objects saved inside registered.
I see lot of people using SharedPreferences, but I don't know how to add items inside the pre-saved hashmap.
You can do it indirectly this way:
//writing into file
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString( key, hashmap.getValue() );
editor.commit();
//reading from file
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
for( i = 0;i < size;i++) )
pref.getString( i , defaultValue );

How do I update a sharedpreference variable in this way?

I have a sharedpreference var with values like these:
key0,value
key1,value
key3,value
key5,value
key6,value
key7,value
key10,value
What I want to do is to get a new sharedpreference value with items sorted sequentially like these:
key0,value
key1,value
key2,value
key3,value
key4,value
key5,value
key6,value
How do I do this?
Thank you in advanced.
You can use a workaround like this:
SharedPreferences shp = context.getSharedPreferences("yourSHP", MODE_PRIVATE);
//begin & end are to integers. For your case: 0 and 6 to get form key0 to key6
for(int i=begin;i<=end;i++){
String value = shp.getString("key"+i, "defaultValue");
//.....Here you can do whatever you want with your values
}
I hope this would help!!
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry<String, String> entry : testMap.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
I did the following workaround. I don't know if there is another faster way to do it:
SharedPreferences shpTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
Map<String,?> keysTH = shpTH.getAll();
List<String> imgTH = new ArrayList<String>();
for(Map.Entry<String,?> entry : keysTH.entrySet()){
imgTH.add(entry.getValue().toString());
}
SharedPreferences newPrefsTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
newPrefsTH.edit().clear().commit();
int contTH = 0;
for(String item : imgTH){
SharedPreferences.Editor editorTH = newPrefsTH.edit();
editorTH.putString("urlTH" + contTH, item);
editorTH.commit();
contTH++;
}
Firstly I copy all the values to a list. Then I empty the sharedpreferences var and finally I put all the values got from the list filled previously in the empty sharedpreferences.

Passing strings to list and deleting them using shared preferences

i wish to, in one activity, put strings in the sharedpreferences, so then, in another activity, i get those strings, put them in a array and display them sequentially. I managed to do this, but i don`t have any idea how can i delete one specified string when asked. These strings will just be scattered on the shared preferences,and i dont know how to keep track of them. I can pass this unique int id to each element. I tried to use LinkedList, but i cannot pass this kind of structure as a shared preferences. I did not managed to make Gson work also. Please help.
Method that gets the string and put on shared preferences:
public void makefavorites(String[] a, String[] b, int id)
{
int idfinal = id%10;
idfinal = idfinal+1;
a[idfinal] = b[idfinal] +"\n" + "\n"+ a[idfinal];
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
Editor edit = prefs.edit();
int temp = prefs.getInt("favorites_size", 0);
edit.putInt("favorites_size", temp+1);
edit.putString("array_" + prefs.getInt("favorites_size", 0), a[idfinal]);
edit.commit();
refreshfavorites();
}
Method that gets those strings, put on array and display it:
public void refreshfavorites()
{
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
//GETS THE ARRAY SIZE
int size = prefs.getInt("favorites_size", 0);
String[] array = new String[size];
for(int i=0; i<size; i++){
array[i] = prefs.getString("array_" + i, null);
}
}
you have to use editor.remove method to delete specific value from arraylist..
public void removeArray(String[] list)()
{
SharedPreferences.Editor editor = mSharedPrefs.edit();
int size = list.length();
for (int i = 0; i < size; i++) {
editor.remove("favorites_size"+i);
}
editor.commit();
}
i hope its useful to you..

Saving an arbritrary length array in SharedPreferences - Android

My objective is to save a field entered in an EditText when the user clicks on a button; in this case it's an IP address. The idea would be to show a list of all valid entered IPs when the user focuses on the EditText, similar to saved searches.
I found this useful piece of code. I need a bit of help explaining it. The code runs putString of all the elements in the String[] array which I think is a collection of all the submitted fields in EditText. How do I create this array if only one field is getting added at a time? I need an explanation of what is happening below.
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i = 0;i < array.length; i++){
editor.putString(arrayName + "_" + i, array[i]);
}
return editor.commit();
}
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
As per your requirement and the code you referenced, I get the following idea:
Untested for erratas:
public boolean saveoneData(String oneTimeData, String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+"_size", 0); // For the first time it gives the default value(0)
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key+ "_" + size, oneTimeData);
editor.putInt(key+"_size", ++size); // Here everytime you add the data, the size increments.
return editor.commit();
}
public String[] loadArray(String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+ "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(key+ "_" + i, null);
return array;
}
But I usually don't use the sharedpreferences for large storage of data because it could make data creation, retrieval and data modifications difficult as the data increases. Hope this is what you want.
Once you collect all EditText values in one String[] array or List<String> or Set<String>;
You don't need to save each array value as separate key-value pair in the SharedPreferences. There is much simpler way to save, which is create Set<String> and save them all values under one key:
editor.putStringSet(arrayName, new HashSet<String>(Arrays.asList(array));
For retrieving you can retrieve them as Set<String> in same manner:
Set<String> ipsSet = sharedPrefs.getStringSet(arrayName, null);
What is happening in the code you posted:
Each value of String array is saved individually under unique key and the size of the array, likewise.
Similarly later each item is retrieved moving in the range 0 to the saved size of the array, which is retrieved at first place from the SharedPreferences

How to store one string and arrayvalue in sharedpreference?

I have array values of up[]={0,0,0,0,0} and view="adult" thesetwo value i want to store and retrieve in from sharedpreference how to do that...
Assuming that you have a list of preferences for you app called MY_PREFS, I'd do this:
SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("arrayLength",up.size());
for(int i=0; i<up.size(); i++){
editor.putInt("up"+String.valueOf(i), up[i]);
}
editor.putString("view", "adult");
To retrieve them do:
SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
int arraySize = settings.getInt("arrayLength");
int up[] = new int[arraySize];
for(int i=0; i<arraySize; i++){
up[i] = settings.getInt("up"+String.valueOf(i));
}
String view = settings.getString("view");
you can do by simple way, like this
SharedPreferences settings = getSharedPreferences("pref_name", 0);
SharedPreferences.Editor editor = settings.edit();
String values="";
for(int i=0; i<yourArray.length; i++){
values+=","+Integer.toString(yourArray[i]);
}
editer.putString("array",values);
editor.putString("view", "adult");
To get those values,
SharedPreferences settings = getSharedPreferences("pref_name", 0);
String[] strArray=settings.getString("array").split(",");
int[] yourArray=new int[strArray.length];
for(int i=0;i<strArray.length;i++){
yourArray[i]=Integer.toParseInt(strArray[i]);
}
Well as far as I have seen you can't directly store an array in shared preferences. You can however use a for loop to save an int with an increasing name and have it call it back the same way when you need it and store it into another array.
for(int i=0; i<numInYourArray; i++){
editor.putInt("up"+i, up[i]);
}
If you aren't sure on how to use Shared Preferences in general look here

Categories

Resources