Saving an arbritrary length array in SharedPreferences - Android - 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

Related

SharedPreferences not saving all the data after restart

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

How to store and access Radio Buttons from Shared Preferences?

There are a lot of questions on SO about saving radio buttons state in Shared Preferences but none of them provide the solution that I'm looking for.
I'm creating 15 radio groups and 4 radio buttons inside each radio group in a for loop. The radio groups have unique id from 1 to 15 and the radio buttons have ids ranging from 100 to 159.
This is the code I use to save radio buttons id:
public void saveArray(int[] array, String arrayName) {
SharedPreferences prefs = getActivity().getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++) {
editor.putInt(arrayName + "_" + i, array[i]);
}
editor.commit();
}
array contains the unique ID of all those radio buttons that are checked and I've tested the above code, it works perfectly but the problem is I can't access it.
This is the code I use to retrieve radio button id:
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
}
}
Like saveArray, loadArray also works. The array is populated by the correct radio button ids.
The problem starts now - I can't access those radio buttons, I can't do findViewById() because that is only available in onCreateView()
So this will not work inside loadArray
for(int i=0; i<size; i++) {
RadioButton radio1 = (RadioButton) findViewById(array[i]);
}
The possible solution to findViewById is storing the views in onCreateView() and then accessing it later. So I created a Radio Button array
RadioButton[] allRadio = new RadioButton[15];
Now inside onCheckedChanged, I'm adding the selected radio buttons to the array:
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton radio = (RadioButton) rootView.findViewById(i);
String selectedValue = radio.getText().toString();
allRadio[radioGroup.getId()-1] = radio;
}
The above code perfectly stores the radio buttons inside the array but now I can't save them! You can store int, string etc.. in Shared Preferences but not radio buttons! The solution to this could be to store radio button id but then the same problem will start all over again that findViewById() is not available.
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
//->put Toast here and check whether your are getting the id's or not. If you
//->are getting it, return arrays of id back to calling method
}
}

Shared Preferences for Arraylist

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

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..

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