Shared preferences to String array - android

I would like to know how I would be able to able achieve getting the strings from my shared preferences(I have already set up), then outputting it to a String array so that my Image Fetcher will be able to read it(It has to be an array for it to read).
In one activity I am setting the shared preferences:
case R.id.FavouriteWallpaper:
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", mImageUrl);
editor.commit();
}
return super.onOptionsItemSelected(item);
}
In another class I am getting the string from shared preferences:
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.getString("imgUrl", null); //Output imgUrl to String Array somehow
// I would like my image fetcher to read a string array that has been fetched from shared preferences.
mImageFetcher.loadImage(Fragment3.imgUrl[position
- mNumColumns], imageView);
return imageView;
}

You can not really save an array to SharedPrerences, but you can store all your urls in a string like CSV (comma separated values) and store it in sharePreferences. You can write a manager that will have 2 methods. One to transform your array to CSV and store and the second get the CSV and transform it to an array.
The second method is to save the data like a JSONArray to do this you also need to write a manager that will have 2 methods also, one to transform your array to JSONArray and store it in Shared Preferences, and the second to transform the jsonArray into your array.

you can get the strings using for loop
examole...
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", mImageUrl);
for(int i=0; i<arraylist.size(); i++)
{
editor.putString("imgUrl"+i, arraylist.get(i).toString());
}
editor.commit();

Related

Store json data sharedpreference and not overwrite

i create app where when user added new data , there is new label
I have tried and it worked, but I wonder how can I make the json that I store in SharedPreferences
do not over write
so I can add 2 or more user json to adapter
Here is my put string file the json variable contain user that added
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
Here is how I can get json from shared preference
try{
String listNewUserAdd = sh.getString("listNewUser","");
JSONObject object = new JSONObject(listNewUserAdd);
for (int i=0; i<object.length(); i++) {
CustomerNew customer = new CustomerNew();
customer.setCustomerName(object.getString("receiverName"));
customer.setAccountId(object.getString("customerReference"));
customer.setId(object.getLong("customerId"));
System.out.println("### GET CUSTOMER NAME "+customer.getCustomerName());
listSortNew.add(customer);
if (listSortNew == null) {
// if the array list is empty
// creating a new array list.
listSortNew = new ArrayList<>();
}
}
I think there are two ways to realize it. One way is when you put data you have to check if it exists.
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
String listNewUser = sharedPreferences.getString("listNewUser","");
if(!TextUtils.isEmpty(listNewUser)){
//covert it the list object
//then add the all new item to it
//finally convert it to json string
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
the other way is to change the SharedPreferences MODE_APPEND
but you must know, it doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased. We usually used MODE_PRIVATE
In the end I suggest you firstly get the data from it, then check if you need change, you can change the data, then save it again.

SharedPreference StringSet to Array Order Issue

Please be patient while I explain my issue:
1) I am storing my preferences via a StringSet as follows:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// Create a new Arraylist with the details of our details
ArrayList <String> newCityFareDetails = new ArrayList<String>();
// Store various values
newCityFareDetails.add(0, String.valueOf(cloneFare.value1()));
newCityFareDetails.add(1, String.valueOf(cloneFare.value2()));
newCityFareDetails.add(2, String.valueOf(cloneFare.value3()));
newCityFareDetails.add(3, String.valueOf(cloneFare.value4()));
newCityFareDetails.add(4, cloneFare.value5());
// Only value 5 is a string, rest are all floats
// Convert to a hashstring, give it the name of our value
Set<String> set = new HashSet<String>();
set.addAll(newCityFareDetails);
editor.putStringSet(extras.getString("startCity"), set);
// And write it to storage
editor.commit();
Now, I'm trying to read it as follows:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Set<String> tryCityFromPrefs = prefs.getStringSet(currentCity, null);
if (tryCityFromPrefs!=null){
// Crude code, but we convert the preferences into a String array
String[] values = tryCityFromPrefs.toArray(new String[tryCityFromPrefs.size()]);
myFare = new Fare(Float.parseFloat(values[0]), Float.parseFloat(values[1]),
Float.parseFloat(values[2]), Float.parseFloat(values[3]), values[4]);
}
Now, problem is that the myFare is not getting initialized properly because the values in the array are scrambled. i.e. the String value that was at the last position when we save is now in the 2nd position. Is this something to do with Sets to String conversion? Or am I missing something obvious?
A Set does not guarantee order. While there are specific Set implementations (e.g., LinkedHashSet) that are ordered, that's not what SharedPreferences uses.
Your options are:
Change your app to not care about the order.
Save the data in SharedPreferences some other way. In this app, for example, I use JsonReader/JsonWriter to save an ArrayList into a single String value.
Save the data in some other fashion (e.g., JSON file, SQLite database with a sequence number to maintain order).

Get Strings from ArrayList and save in Shared Preferences

I have an ArrayList that can contain 1 to 15 strings. Those strings need to be saved in my shared preferences, now I know how to iterate trough the array to get the strings. What I don't know, is there a clean way to dynamically add the strings to my shared preferences file? I could do this on a sluggish way by creating 15 strings and using an if statement to fill the shared preference, but I would like to know if there is a better way.
Thank you.
If its about naming, you can use something like this:
public static final String mPrefix = "mArray";
SharedPreferences prefs;
prefs = this.getSharedPreferences("PREF", 0);
prefsEditor = appSharedPrefs.edit();
//mAL is your ArrayList
for(int i=0; i<mAl.size(); i++){
prefsEditor.putString(mPrefix + "-" + i, mAl.get(i));
}
prefsEditor.commit();
You can use the putStringSet method available in SharedPreferences.Editor to store string arrays. For example:
String[] array = new String[]{"this", "is", "a", "string", "array"};
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putStringSet("myKey", new HashSet<String>(Arrays.asList(array)));
edit.commit();
Or if your API is below 11 then you may convert your string array into a single string and save it just like an ordinary string. For example:
edit.putString("myKey", TextUtils.join(",", array));
and later use the following to rebuild your array from string:
array = TextUtils.split(sharedPrefs.getString("myKey", null), ",");
Mainly to edit the shared prefernces data you need to take the Editor Object from it so you could edit it freely so to put data in it:
SharedPrefernces preferences = mContext.getSharedPreferences(MODE_PRIVATE);
Editor prefEditor = preferences.edit();
prefEditor.putString("this is a key object","this is value of the key");
You can also put inside different kinds of object for example : boolean , int , float , double and etc....
Just look up the editor class in android developers website...
In order to read the data from the sharedPrefrences it is even more simplier
SharedPrefrences pref = mContext.getSharedPreferences(MODE_PRIVATE);
pref.getString("the key of the value");

Issue with shared preference

I am using Android 2.1 sdk and I am trying to save user loggin session in to Shared preferences, the thing is after saving the value to the shared preference I am unable to retrive it. Here I am pasting the code I used to save and fetch value from SharedPrefrence.
public void setValue(String name, String value, String prefName) {
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
sharedPref.edit().putString(name, value);
sharedPref.edit().commit();
}
public String getValue(String name, String prefName) {
String value = null;
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
value = sharedPref.getString(name, value);
return value;
}
Did i miss some thing in this code, I am not retrieving any exceptions while saving and retrieving the value. Thanks for any help.
Every call to edit() returns you a new Editor instance. So you get an instance, make a change and leave it alone. Then you get a second one and commit that without changes, which results in no value changes in the preferences.
Rather chain in the commit():
sharedPref.edit().putString(name, value).commit();
Alternatively break it up into multiple lines with one specific instance:
Editor e = sharedPref.edit();
e.putString(name, value);
e.commit();
private SharedPreferences myPrefs;
myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Mobile_no", getText_no.getText().toString().trim());
prefsEditor.commit();
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
myPrefs.getString("Mobile_no", "");
try this one code work

Android store array in preferences

I know only primitives can be stored in the android preferences, but do arrays count? Can I store an array of, say, Strings or booleans in an android preference?
Only if you turn the array into a string.
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
for(int n =0;n<LevelMenu.buttonState.length;n++){
LevelMenu.buttonState[n]= (byte) settings.getInt("levelsave"+n,0);
}
Above will get and populate the array and below will depopulate and save.
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
for(int n =0;n<LevelMenu.buttonState.length;n++){
editor.putInt("levelsave"+n,LevelMenu.buttonState[n]);
}
editor.commit();

Categories

Resources