I am trying to save an int array into the shared preferences.
int myInts[]={1,2,3,4};
SharedPreferences prefs = getSharedPreferences(
"Settings", 0);
SharedPreferences.Editor editor = prefs
.edit();
editor.putInt("savedints", myInts);
Since the putInt method does not accept int arrays, I was wondering if anyone knew another way to do this. Thanks
Consider JSON.
JSON is well integrated into Android and you can serialize any complex type of java object. In your case the following code would be suited well.
// write
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray arr = new JSONArray();
arr.put(12);
arr.put(-6);
prefs.edit().putString("key", arr.toString());
prefs.edit().commit();
// read
try {
arr = new JSONArray(prefs.getString("key", "[]"));
arr.getInt(1); // -6
} catch (JSONException e) {
e.printStackTrace();
}
you can add only primitive values to sharedpreference ......
refer this doc:
http://developer.android.com/reference/android/content/SharedPreferences.html
You can serialize an array to String using TextUtils.join(";", myInts) and the deserialize it back using something like TextUtils. SimpleStringSplitter or implement your own TextUtils.StringSplitter.
If your integers are unique, perhaps you can use putStringSet (see docs). Otherwise you have to resort to serializing / formatting your integer array as String, as suggested by other answers.
Related
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.
I use the following helper to save user input to sharedpreference:
protected void storeData(SharedPreferences.Editor editor,
String key, EditText et) {
String content = et.getText().toString();
if ("".equals(content)||" ".equals(content)) {
editor.remove(key);
} else {
editor.putString(key, content);
}
}
then
number1 = (EditText)findViewById(R.id.number1);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
storeData(editor,"number1", number1);
editor.commit();
I wish to ask if how can I retrieve that value as a integer, then use it for some calculation.
I been searching and found this , found that they use editor.putInt(key,content);
But is that possible to extract the value as integer straight from my method?
thank you.
Your storeData() method is setting a string (putString()). Shared prefs store typed values distinctly different. That is, you cannot put "1" as a string then get it our later as an integer.
You need to use put/getInt() consistently. Alternatively you could store it as a string, and again consistently get it as a string and coerce it to an int as you need.
Your really should be using putInt(), but you can also use Integer.parseInt("some string") to convert your String value to an integer.
Use editor.commit() inside the else part
A suggestion:
use editor.apply() instead of editor.commit() as commit handles the job in foreground whereas apply handles that asynchronously.
I know, the question has been asked long time agao. I came up with similar situation. So, the might help someone in the future.
//for integer values
port = (EditText) findViewById(R.id.devicePort);
int devicePort = Integer.parseInt(port.getText().toString());
editor.putInt(getString(R.string.devicePort), devicePort);
editor.apply();
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).
I want to store an ArrayList<class> in shared preference. But the error showed up in editor3.putString("Array", nama);. I guess the error caused by putString. What sould i do?
Should I used another method to storing arraylist ?
ArrayList<Class> nama = new ArrayList<Class>(9);
nama.add(dragsandal.class);nama.add(Terimakasih.class);
nama.add(Ludah.class);
nama.add(Permisi.class);
nama.add(Tolong.class);
nama.add(Maaf.class);
SharedPreferences pref3 = getApplicationContext().getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor3 = pref3.edit();
editor3.putString("Array", nama);
editor3.apply();
You should use putStringSet(Set<String>) to store sets (Lists with unique elements). SharedPreferences do not provide a method to store lists directly.
You can easily convert your list to a set using e.g. new HashSet<String>(yourList);
If you need to store a list, you can serialize your list to a String, e.g. by using Gson and storing the json value. Then putString(json) would be correct.
First I don't think there is a way to store lists in Shared preferences. Second it is not a good idea. In your case,I would consider using Sqlite database. It would make things easier.
You can't store a Class type object in SharedPreferences. Also you can't store Lists. If you really need to, you can store the full name of the class object as a String. Then when you read the value back you, you can use Class.forName() to convert that string back to a class. It seems weird, but you can do it.
You could try this to save and restore a set of class names:
Set<String> set = new HashSet<String>();
set.put(Terimakasih.class.getName());
set.put(Ludah.class.getName());
set.put(Permisi.class.getName());
set.put(Tolong.class.getName());
set.put(Maaf.class.getName());
SharedPreferences pref3 = getApplicationContext().getSharedPreferences("set", MODE_PRIVATE);
SharedPreferences.Editor editor3 = pref3.edit();
editor3.putStringSet("set", set);
editor3.apply();
Set<String> strings = pref3.getStringSet("set", Collections.emptySet());
Set<Class> classes = new HashSet<Class>();
for (String s : strings) {
classes.put(Class.forName(s));
}
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");