I am working with SharedPrefrences. I have multiple shared preferences in pref. I am changing values 0 to n-1 in a loop while, other value is User Score. Maybe there is some problem with my using of commit(), but the value is not updated. Can you suggest what should I do?
SharedPreferences pref = getApplicationContext().getSharedPreferences("Scorepref", 0);
SharedPreferences.Editor editor = pref.edit();
for (int i = 0; i < mQuestionBank.length; i++) {
editor.putBoolean(Integer.toString(i), false);
editor.commit();
}
mAnswered.setText( "0/" +Integer.toString(mQuestionBank.length));
mScoreval = 0;
mAnswered_count=0;
editor.putInt("User_score", 0);
editor.commit();
mScore.setText("0");
You didn't show us the code how you're trying read the data from prefs but anyway in your case, if you're not able to read the data by prefs.getBoolean then you can iterate over pref.getAll() like:
if (pref.getAll() != null) {
for (int i = 0; i < mQuestionBank.size(); i++) {
if (pref.getAll().get(String.valueOf(i)) instanceof Boolean) {
final Boolean yourSavedBoolean = (Boolean) pref.getAll().get(i);
}
}
}
Or if you need only one value then:
if (pref.getAll() != null) {
Boolean yourSavedBoolean = false;
if (pref.getAll().get("0") != null && pref.getAll().get("0") instanceof Boolean) {
yourSavedBoolean = (Boolean) pref.getAll().get("0");
}
}
Related
I'm very new to coding in android, so I barely know any of the syntaxes. I am defining a variable in MainActivity.java and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
Then retrive it with
int number = sharedPref.getInt("key for value";
Sometimes you need to specify a default value like:
SharedPref.getBoolean("is first lunch",true);
Good luck
Use SharedPreference for saving value use this code
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
here are two method
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
Store in Preference if value is 0 else get stored value
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
Retrieve from Preference
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
Just copy and paste above code
For my app, I need to save a simple SparseBooleanArray to memory and read it later.
Is there any way to save it using SharedPreferences?
I considered using an SQLite database but it seemed overkill for something as simple as this. Some other answers I found on StackOverflow suggested using GSON for saving it as a String but I need to keep this app very light and fast in file size. Is there any way of achieving this without relying on a third party library and while maintaining good performance?
You can use the power of JSON to save in the shared preferences for any type of object
For example SparseIntArray
Save items like Json string
public static void saveArrayPref(Context context, String prefKey, SparseIntArray intDict) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray json = new JSONArray();
StringBuffer data = new StringBuffer().append("[");
for(int i = 0; i < intDict.size(); i++) {
data.append("{")
.append("\"key\": ")
.append(intDict.keyAt(i)).append(",")
.append("\"order\": ")
.append(intDict.valueAt(i))
.append("},");
json.put(data);
}
data.append("]");
editor.putString(prefKey, intDict.size() == 0 ? null : data.toString());
editor.commit();
}
and read json string
public static SparseIntArray getArrayPref(Context context, String prefKey) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(prefKey, null);
SparseIntArray intDict = new SparseIntArray();
if (json != null) {
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
intDict.put(item.getInt("key"), item.getInt("order"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return intDict;
}
and use like this:
SparseIntArray myKeyList = new SparseIntArray();
...
//write list
saveArrayPref(getApplicationContext(),"MyList", myKeyList);
...
//read list
myKeyList = getArrayPref(getApplicationContext(), "MyList");
Write the values separately, and keep a list of the names of the values you write:
SparseBooleanArray array = //your array;
SharedPreferences prefs = //your preferences
//write
SharedPreferences.Editor edit = prefs.edit();
Set<String> keys = new HashSet<String>(array.size());
for(int i = 0, z = array.size(); i < z; ++i) {
int key = array.keyAt(i);
keys.add(String.valueOf(key));
edit.putBoolean("key_" + key, array.valueAt(i));
}
edit.putStringSet("keys", keys);
edit.commit();
//read
Set<String> set = prefs.getStringSet("keys", null);
if(set != null && !set.isEmpty()) {
for (String key : set) {
int k = Integer.parseInt(key);
array.put(k, prefs.getBoolean("key_"+key, false));
}
}
String sets are supported since API 11.
You could instead build a single csv string and split that rather than storing the set.
You can serialize the object to a byte array and then probably base64 the byte array before saving to SharedPreferences. Object serialization is really easy, you don't need a third party library for that.
public static byte[] serialize(Object obj) {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
ObjectOutputStream objectOS = new ObjectOutputStream(byteArrayOS);
objectOS.writeObject(obj);
objectOS.flush();
return byteArrayOS.toByteArray();
}
public static Object deserialize(byte[] data) {
ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(data);
ObjectInputStream objectIS = new ObjectInputStream(byteArrayIS);
return objectIS.readObject();
}
The code above doesn't have try catch block for simplicity. You can add it on your own.
I have been doing this as the following by using Gson
To save sparseboolean array in SharedPreference:
public void SaveSparseBoolean() {
SparseBooleanArray booleanArray = new SparseBooleanArray();
SharedPreferences sP;
sP=context.getSharedPreferences("MY_APPS_PREF",Context.MODE_PRIVATE)
SharedPreferences.Editor editor=sP.edit();
Gson gson=new Gson();
editor.putString("Sparse_Array",gson.toJson(booleanArray));
editor.commit();
}
To get the SparsebooleanArray from SharedPreferences
public SparseBooleanArray getSparseArray() {
SparseBooleanArray booleanArray;
SharedPreferences sP;
sP = context.getSharedPreferences("MY_APPS_PREF", Context.MODE_PRIVATE);
Gson gson=new Gson();
booleanArray=gson.fromJson(sP.getString("Sparse_Array",""),SparseBooleanArray.class);
return booleanArray;
}
I have a listview with choice mode, and it working. I want to save that checked item to shared preference, then use it in another activity. But, my SharedPreferences doesn'nt save my string correct, and save another file call DATA_Preferences that i never call in my code.
The result is my Next activity get wrong value..
Here is my code that i use to save my string and call it use by another activity:
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>();
// Item position in adapter
SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
// Add slected if truee
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat()));
prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng()));
}
prefsEditor.commit();
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = String.valueOf(selectedItems.get(i));
}
Bundle b = new Bundle();
Location location = new Location("POINT_LOCATION");
for (int i = 0; i < checked.size(); i++) {
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0));
double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0);
double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0);
prefsEditor.commit();
b.putDouble("Latitude" + i, latitude );
b.putDouble("Longitude" + i, longitude);
}
int banyakPilih = checked.size();
b.putInt("banyakPilih", banyakPilih);
Intent intent = new Intent(getApplicationContext(),
HasilPilihanActivity.class);
// Create a bundle object
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I save my Prefernces in DATA_COOR.xml file name, it save my string, but i got another file that save my preference with file name DATA_Preferences in my Explorer. Some body can give me solution? Thanks before..
Define private SharedPreferences mediaPrefs = null;
put this on your constructor mediaPrefs = this.getSharedPreferences("Testing", 1);
put below method to the source:
public void storeStateString(String prefsKeys, Float prefsValue) {
SharedPreferences.Editor prefEditor = mediaPrefs.edit();
prefEditor.putFloat(prefsKeys, prefsValue);
prefEditor.commit();
}
Use this method to store the state like:
storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));
and now you can get this preference through:
Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l");
where 2.0l is defalut value if mediaPrefs is null;
Let me know if any issues regarding that.
Hi i am new to Android development ,
How to show Custom Listview with check box in Android SDK. I need selected checkbox should be selected before no need to select.
For example i have a favarote view in that i selected some items previously should appear as selected when i have to go that view.
Please any one help me.
Thanks in advance
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
savedNames = getSavedItems();
prefEditor.putString(SETTING_TODOLIST, savedNames);
prefEditor.commit();
}
private String getSavedItems() {
String savedNames = "";
int count = this.listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (FPhoneListCheckboxAES.phonelist.get(i).getChecked() == true) {
if (savedNames.length() > 0) {
savedNames += ","
+ FPhoneListCheckboxAES.phonelist.get(i).getname();
savedPhoneno += ","
+ FPhoneListCheckboxAES.phonelist.get(i).getphoneNo();
} else {
savedNames += FPhoneListCheckboxAES.phonelist.get(i).getname();
savedPhoneno += FPhoneListCheckboxAES.phonelist.get(i)
.getphoneNo();
}
}
}
return savedNames;
}
check the link this will help u a lot
http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/
I want to save/recall an integer array using SharedPreferences. Is this possible?
You can try to do it this way:
Put your integers into a string, delimiting every int by a character, for example a comma, and then save them as a string:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int[] list = new int[10];
StringBuilder str = new StringBuilder();
for (int i = 0; i < list.length; i++) {
str.append(list[i]).append(",");
}
prefs.edit().putString("string", str.toString());
Get the string and parse it using StringTokenizer:
String savedString = prefs.getString("string", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int[] savedList = new int[10];
for (int i = 0; i < 10; i++) {
savedList[i] = Integer.parseInt(st.nextToken());
}
You can't put Arrays in SharedPreferences, but you can workaround:
private static final String LEN_PREFIX = "Count_";
private static final String VAL_PREFIX = "IntValue_";
public void storeIntArray(String name, int[] array){
SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit();
edit.putInt(LEN_PREFIX + name, array.length);
int count = 0;
for (int i: array){
edit.putInt(VAL_PREFIX + name + count++, i);
}
edit.commit();
}
public int[] getFromPrefs(String name){
int[] ret;
SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE);
int count = prefs.getInt(LEN_PREFIX + name, 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] = prefs.getInt(VAL_PREFIX+ name + i, i);
}
return ret;
}
Here's my version, based on Egor's answer. I prefer not to use StringBuilder unless I'm building an enourmous string, but thanks to Egor for using StringTokenizer -- haven't made much use of this in the past, but it's very handy! FYI, this went in my Utility class:
public static void saveIntListPrefs(
String name, Activity activity, List<Integer> list)
{
String s = "";
for (Integer i : list) {
s += i + ",";
}
Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
editor.putString(name, s);
editor.commit();
}
public static ArrayList<Integer> readIntArrayPrefs(String name, Activity activity)
{
SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE);
String s = prefs.getString(name, "");
StringTokenizer st = new StringTokenizer(s, ",");
ArrayList<Integer> result = new ArrayList<Integer>();
while (st.hasMoreTokens()) {
result.add(Integer.parseInt(st.nextToken()));
}
return result;
}
I like to use JSON, which can be stored and retrieved as a string, to represent any complex data in SharedPreferences.
So, in the case of an int array:
public void setPrefIntArray(String tag, int[] value)
{
SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
String s;
try
{
JSONArray jsonArr = new JSONArray();
for (int i : value)
jsonArr.put(i);
JSONObject json = new JSONObject();
json.put(tag, jsonArr);
s = json.toString();
}
catch(JSONException excp)
{
s = "";
}
prefEditor.putString(tag, s);
prefEditor.commit();
}
public int[] getPrefIntArray(String tag, int[] defaultValue)
{
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String s = pref.getString(tag, "");
try
{
JSONObject json = new JSONObject(new JSONTokener(s));
JSONArray jsonArr = json.getJSONArray(tag);
int[] result = new int[jsonArr.length()];
for (int i = 0; i < jsonArr.length(); i++)
result[i] = jsonArr.getInt(i);
return result;
}
catch(JSONException excp)
{
return defaultValue;
}
}
The beauty is that the same idea can be applied to any other complex data representable as a JSON.
Two solutions:
(1) Use http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
It has split/join functions that let you join and split the integers in one liners:
StringUtils.join([1, 2, 3], ';') = "1;2;3"
StringUtils.split("1;2;3", ';') = ["1", "2", "3"]
You'd still have to convert the strings back to integers, though.
Actually, for splitting java.lang.String.split() will work just as fine:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
(2) Use the SharedPreferences.putStringSet() (API 11):
SharedPreferences.Editor editor = preferences.edit();
int count = this.intSet.size();
if (count > 0) {
Set<String> theSet = new HashSet<String>();
for (Long l : this.intSet) {
theSet.add(String.valueOf(l));
}
editor.putStringSet(PREFS_KEY, theSet);
} else {
editor.remove(PREFS_KEY);
}
editor.commit();
And to get it back:
Set<String> theSet = this.preferences.getStringSet(PREFS_KEY, null);
if (theSet != null && !theSet.isEmpty()) {
this.intSet.clear();
for (String s : theSet) {
this.intSet.add(Integer.valueOf(s));
}
}
This code does not catch the NPEs or NumberFormatExceptions because the intSet is otherwise assured to not contain any nulls. But of course, if you cannot assure that in your code you should surround this with a try/catch.
Here is how the "convert to comma-separated String" solution could look in Kotlin, implemented as extension functions:
fun SharedPreferences.Editor.putIntArray(key: String, value: IntArray): SharedPreferences.Editor {
return putString(key, value.joinToString(
separator = ",",
transform = { it.toString() }))
}
fun SharedPreferences.getIntArray(key: String): IntArray {
with(getString(key, "")) {
with(if(isNotEmpty()) split(',') else return intArrayOf()) {
return IntArray(count(), { this[it].toInt() })
}
}
}
That way you can use putIntArray(String, IntArray) and getIntArray(String) just like the other put and set methods:
val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
prefs.edit().putIntArray(INT_ARRAY_TEST_KEY, intArrayOf(1, 2, 3)).apply()
val intArray = prefs.getIntArray(INT_ARRAY_TEST_KEY)
I went for the below solution, it's the least verbose of what I could see in this thread (in my case I wanted to have a set as a collection). "value" is the of type Set<Int>.
Save:
sharedPreferences.edit {
if (value.isNotEmpty()) {
putStringSet(key, hashSetOf(*value.map { it.toString() }.toTypedArray()))
} else {
remove(key)
}
}
Retrieve:
val stringSet = sharedPreferences.getStringSet(key, null)
if (stringSet.isNullOrEmpty()) return emptySet()
return setOf<Int>(*stringSet.map { Integer.valueOf(it) }.toTypedArray())
You can only save primitive values in sharedPreference. Use Sqlite instead.