I have an Array called Upvalthat has 16 Integer values that I would like to store in my SharedPreferences without creating individual ones for each, but SharedPrefernces won't allow Array's, what is the simplest way of doing this? The declaration looks something like this:
Integer[] UpVal = new Integer[16];
You can store it as a String by transforming it:
Arrays.toString(upVal)
To get it back and convert a String to an Integer array is trivial.
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.
Related
Ultimately I am trying to store an Int Array in Shared Preferences but I know Kotlin doesn't support that. So I am converting my Int Array to a String Array using the method here:
How can I store an integer array in SharedPreferences?
My issue is that I am struggling to put in a default value for the getStringSet method:
private fun loadIntScoreArray() {
val prefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE)
//TODO: Load the String array
var default = emptyList<String>()
avgScoreArrayString = prefs.getStringSet(AVG_SCORE_ARRAY, default)
}
However default is not an acceptable object in the prefs.getStringSet(AVG_SCORE_ARRAY, default) line. The error is confusing because it seems contradictory:
Required: MutableList
Found: (Mutable)Set!
Required: (Mutable)Set!
Found: MutableList
There is few things you need to know. Since API 11 you can only store plain objects or sets to shared preferences. You can convert your list to set, but it can be lossy conversion in your list contain duplicates.
If you want to use sets you should call it like this:
//to get
prefs.getStringSet(AVG_SCORE_ARRAY, emptySet<String>()))
//to set
prefs.edit().putStringSet(key, AVG_SCORE_ARRAY)
The other way is to join array to a single string using join operation. Here is a doc for you https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to.html
To be honest both of these ways are not the perfect solutions. If it is production application and I recommend using persistance library like Room, Realm etc.
Hope it helps.
Edit.
If you are hundred percent sure you are going to have 5 ints stored (and it is not gonna change in a near or distant future), using database could be overkill. I recommend using joining to single string and storing it as single string or just store 5 independent int values. There is no point in complicating simple things.
I have 10 values (int and boolean) which I want to save, so I can load them whenever I need them (I need the different values at the same time which makes it easy). Is it overkill if I make one JSONString/(JSONObject) out of 10 values and save that string in SharedPreferences? Is it better practice to just store every single value like this:
editor.putInt("Volume", VolumeBar.getProgress());
editor.putInt("Difficulty", DifficultyBar.getProgress());
[...]
and to get it from SharedPreferences like this:
Volume = mPrefs.getInt("Volume", maxVolume);
Difficulty = mPrefs.getInt("Difficulty", 0);
I think it's better to create model with ten variables and convert it
to JsonString because you just put one strng value in SharedPref but it's issue that if you want to update one of it's values you have to retrieve the whole object and modify and set it back in sharedPref
I want to save Integer ArrayList to sharedpreferrence with HashSet, but I can only do this with String ArrayList. I have tried converting each of the integers to strings but then I have to change a lot of code. Maybe there is an easier way?
https://i.stack.imgur.com/ba4XB.png
There is no support for lists of items in SharedPreferences (except for String). The easiest way to do this is to write yourself a convenience method that converts an array of integers into a String and vice versa. Then store the String in SharedPreferences.
can i store two or more values with same key using SharedPreferences in android? If no, please tell me how to store values of username, first name, password etc when many users register in registration app?
Ex:
person A registered with username="john12", first name="john" and DOB="06/06/2000".
person B registered with username="arun89", first name="arun" and DOB="08/11/1989".
Now, I want to store these values in SharedPreferences and retrieve them later. Is it possible using SharedPreferences? If not, Please tell me how to do in other way.
Thank you in advance.
I woud consider creating a JSONObject and add the fields you want to store as a key:value pair.
json.putString(key, value);
You can then store the json object in it's string representation with json.toString() and restore it later with
JSONObject jo = new JSONObject(jsonString);
String value = jo.getString(key);
JSONObject also offeres different data types beside strings.
It really depends on how much data you want to store. Depending on that I would choose SharedPreferences or a SQLite implementation.
You cannot store these values directly (as ones added latter will overwrite previously added) but you can always store Parcelable and put your data into it
For your case it is better use SQLIte database.But if you want to use shared preference it is still possible.You have to use a key with additional index to remember different user like
UserName1:arun
UserName2:john
You have to remember the total number of user.Then can maintain all of them.you can also use other data structure like hashmap to maintain data for the shared preference.
I dont't think it is possible, as you don't know the number of users.
You could try to separate the users with commas, but that's lame.
You should consider using SQLite database.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Then you have to store a array List of user objects first create a class userInfo then create a array List type of userInfo then store the data in this list and put a serialize-able object in SharedPreferences.
You can also store them on a single key called "registers" as string. Concatenate each register to preference. Put ";" (or any other characther you want) between each register. Then parse the string and use the values.
Key: registers
Value: "username=john12, first name=john, DOB=06/06/2000;username=mike12, first name=mike, DOB=06/07/2012"
Using split method of String will give you a list of registers as String.
registers.split(";");
Splitting again with "," will give you properties of each register.
I am trying to create an array like this ["stringone","stringtwo"] and pass it to the webserver. When I tried doing making it with a string array like String[]={"stringone","stringtwo"] it passed in something weird {"userids":"[Ljava.lang.String;#406fe4b8"} how should I be constructing my JSON array if not by using string arrays?
Thanks
If you want to create JSONArray from List or array, you can use constructor, which takes Collection:
String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.asList(data));
The easiest way is to create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.