How to store array in an sharedpreferences in android - java

I am building an android application where the user selects his event from spinner tool.
The Spinner tool displays the array list that user had selected first time the application is launched.
Now I had parsed the array list from app launch page to spinner activity class an using it in spinner tool success full now.
Here is code:
public static ArrayList<String> array;
Here, the name array has the arraylist.
I need to store this in sharedprefrences. How can I do this ?
I am new to android.

I don't suggest using putStringSet() since it will screw up your arrayorder.
I suggest running a for loop over your array and giving them different key names. + in the end adding another String, that tells you how long the array is once you wanna read out the strings of the SharedPreferences.
General settings:
SharedPreferences sharedPreferences = getSharedPreferences("YOURKEYFILE", Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
Save String Array:
for (int i = 0; i < array.size(); i++) {
sharedPreferencesEditor.putString("StringArrayElement" +i, array.get(i));
}
sharedPreferencesEditor.putInt("StringArrayLength", array.size());
sharedPreferencesEditor.commit();
Read String Array:
array.clear();
for (int i = 0; i < sharedPreferencesEditor.getInt("StringArrayLength", 0) {
array.add(sharedPreferencesEditor.getString("StringArrayElement" +i, "");
}
NOTE:
The above code is untested! Community correct me there if you find mistakes.

You can save your array as Serializable object.
//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(ARRAY, ObjectSerializer.serialize(array));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
And to retrieve it from SharedPreferences:
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
array = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString(ARRAY,
ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
You can get ObjectSerializer.java from here

This code help to you maybe.You save list item by counter i.
for(int i=0;i<list.size();i++)
{
editor.putString(list.get(i)+i, list.get(i));
editor.commit();}
for(int i=0;i<list.size();i++)
{
preferences.getString(list.get(i)+i, "");
}

It's better to go with Set<String> as API version 11 introduced methods putStringSet and getStringSet which allows the developer to store a list of string values and retrieve a list of string values, respectively.
Save list
// Save the list.
editor.putStringSet("array", myStrings);
editor.commit();
Fetch list
// Get the current list.
SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("array", new HashSet<String>());

Related

Storing a 1D array of strings in Shared Preferences

I have two arrays, the first consists of 9 buttons. The second can hold 9 Strings. I have a method called getPlayerChoiceText to populate the String array with the text that is set on each button from the playerchoice Array. How can I save this text using SharedPreferences?
private String[] getPlayerChoiceText()
{
playerchoiceText[0] = playerchoice[0].getText().toString();
playerchoiceText[1] = playerchoice[1].getText().toString();
playerchoiceText[2] = playerchoice[2].getText().toString();
playerchoiceText[3] = playerchoice[3].getText().toString();
playerchoiceText[4] = playerchoice[4].getText().toString();
playerchoiceText[5] = playerchoice[5].getText().toString();
playerchoiceText[6] = playerchoice[6].getText().toString();
playerchoiceText[7] = playerchoice[7].getText().toString();
playerchoiceText[8] = playerchoice[8].getText().toString();
return playerchoiceText;
}
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
playerchoiceText = getPlayerChoiceText();
}
I have got the same problem. I solved it by using JSONArray.
JSONArray choices = new JSONArray();
choices.put("1");
choices.put("2");
choices.put("3");
// Save
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("choices", choices.toString());
// Retrieve
choices = new JSONArray(sharedPreferences.getString("choices", "[]"));
In this way, you can easily do Insert and Delete operations. I hope this helps.
Android's SharedPreferences operates as a key value store, and does not allow you to directly store Java objects. So, representing your player choice text values as a map would make more sense, if you want to store them using shared preferences.
There is one trick you might be able to use here, if you wanted to continue representing your choice texts as an array. You could store the texts using a delimiter, e.g. pipe:
String choices = String.join("|", playerchoiceText);
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
prefs.edit().putString("choices", choices).apply();
And then, on the way out:
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
String[] playerchoiceText = prefs.getString("choices", "").split("\\|");
Use put/getStringSet():
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String[] playerchoiceText = getPlayerChoiceText();
editor.putStringSet("player_choice", new HashSet<T>(Arrays.asList(playerchoiceText));
editor.commit();
}

How can I stop my arraylist being put multiple times into my shared preferences file?

The arraylist should be of the form, [{"12345"}, {"67890"}, etc...]
But when I close my app - I mean press the back button the amount of times it takes to get back to the Android home screen - and then restart it, I see MatchingContactsAsArrayListis[{"12345"}, {"67890"}, etc...,{"12345"}, {"67890"}, etc...]
If I close it twice, the arraylist comes up 3 times and so on, it keeps getting longer. It should just display each value once.
I thought editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
would take care of this.
Here's my code:
#Override
public void onResponse(String response) {
//convert the JSONArray, the response, to a string
String MatchingContactsAsString = response.toString();
//make an arraylist which will hold the phone_number part of the MatchingContacts string
MatchingContactsAsArrayList = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(MatchingContactsAsString);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingContactsAsArrayList.add(obj.getString("phone_number"));
}
SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
Gson gsonMatchingContactsAsArrayList = new Gson();
String jsonMatchingContactsAsArrayList = gsonMatchingContactsAsArrayList.toJson(MatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", jsonMatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
editorMatchingContactsAsArrayList.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
SharedPreferences.remove() method takes in the key that you used to save.
Which in this case is "MatchingContactsAsArrayList".
And actually, you don't need to use remove(), because putString() with an existing key, will override that value. Please make sure that the data from response is correct.

How to save and retrieve an arraylist of strings with the same order, using shared preferences

i am new to Android and i try to complete my first android app. I have an arraylist of strings(which i have adapted into a listview) and i add different strings by pressing different buttons. The problem is that when the app closes, the arraylist loses all the data, and i have read that sharedpreferences class can solve this problem.I tried that, and i retrieved the arraylist back, but not with the same order as it was when i saved it. So, how can i retrieve the arraylist with the same order?
Thanks in advance!
the EASIEST way to save arraylist in sharedpreferences is convert it into JSON and 100% in the same order when you get it
String list = new Gson().toJson(your_list);
shared.putString("KEY", list).apply();
then, to convert it back
List<Object> list = new Gson().fromJson(jsonString, new TypeToken<ArraList<Object>>(){}.getType());
If you're really interested on doing that using SharedPreferences instead of a database, you could try to save the Strings using their position on the array as the key on the preferences file.
You can achieve that with the snippet below:
private String prefName = "preferences";
/**
* Save the arraylist of Strings in a preferences file.
*/
public void saveArray(Context context, ArrayList<String> myArray) {
SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
for (int i = 0; i < myArray.size(); i++) {
editor.putString(String.valueOf(i), myArray.get(i));
}
editor.commit();
}
/**
* Reads the saved contents in order.
*/
public ArrayList<String> readArray(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
int size = sharedPref.getAll().size();
ArrayList<String> ret = new ArrayList<>();
for (int i = 0; i < myArray.size(); i++) {
ret.add(i,sharedPref.getString(String.valueOf(i)));
}
return ret;
}
The preference file should look something like this:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="0">My String</string>
<string name="1">My second String</string>
</map>

Creating arraylist from a string with shared preferences

I want to know how to take a simple string that is being saved in shared preferences but then save each one of those strings and display them into an array list. The user will save the string once a day. And I want the strings to display as an array list. Here's the code for what I'm working with. I have "physical_fragment.java"(SAVES THE DATA) & "MainActivity.java"(LOADS THE DATA).
PHSYICAL_FRAGMENT.JAVA
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
MAINACTIVITY.JAVA
resultPhysical= (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String result= sharedPreferences.getString("result",DEFAULT);
if (result.equals(DEFAULT))
{
Toast.makeText(this, "No data found", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(this, "Load Successful", Toast.LENGTH_LONG).show();
resultPhysical.setText(result);
}
I'd say use GSON for that.
To convert a list of strings to JSON to be stored in preferences you use this:
List<String> list = ...
Type type = new TypeToken<List<String>>(){}.getType();
String json = gson.toJson(list, type);
and store json in SharedPreferences using putString.
To read from SharedPreferences you use something like this:
String result = sharedPreferences.getString("result", DEFAULT);
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = gson.fromJson(result, type);
you can do as follows:
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
ArratList<String> dataList;
String data = "";
for(String itemData:dataList){
data = itemData + String.format(stringDate, date) + " - " + text_view5.getText().toString()+ "/";
editor.putString(data);
}
editor.commit();
Now get the string from Shared preference and split it.
String result= sharedPreferences.getString("result",DEFAULT);
String[] splited = str.split("/");
This helps with out having support of Libraries which can effect size of apk file

Create a List of saves from one button

I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}
You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}

Categories