I am trying to save some String data using SharedPreference.
Here is my code
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
// LOAD
String str = mySharedPref.getString("hello", ""); // I expect "world"
But it only has an empty string!
Meanwhile,
SharedPreference.Editor editor = mySharedPref.edit();
editor.putString(...);
editor.commit();
This worked....
I thought mySharedPref.edit() returns a reference and makes the code above and below the same.
I am confused now. X(
See this solution
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
in your code:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
You called edit() each time you put a String but you didn't call commit() after it so your changes is not saved. You should change to this:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world")
.putString("my", "code");
.commit();
edit() method in SharedPreference returns NEW INSTANCE of the Editor interface. I found the comment explaining it in SharedPreferences.java file came with sdk.
Any actions performed on the new instance will be independent from other instances.
In the first part of my code, by calling edit() multiple times, I was performing actions on each independent instance.
It was interesting to notice that edit() returns a new instance instead of a reference.
/**
* Create a new Editor for these preferences, through which you can make
* modifications to the data in the preferences and atomically commit those
* changes back to the SharedPreferences object.
*
* Note that you must call {#link Editor#commit} to have any
* changes you perform in the Editor actually show up in the
* SharedPreferences.
*
* #return Returns a new instance of the {#link Editor} interface, allowing
* you to modify the values in this SharedPreferences object.
*/
Editor edit();
Related
I am working on an app for Android and can't figure out the error or mistake which I am making. I am searching for the error for more than 4 hours.
I am getting the following Exception working with SharedPreferences:
E/AndroidRuntime: FATAL EXCEPTION: main
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:235)
at de.immozukunft.quicksteuer.QuickSteuerActivity.updateTextView(QuickSteuerActivity.java:56)
at de.immozukunft.quicksteuer.QuickSteuerActivity.onCreate(QuickSteuerActivity.java:36)
But I am not doing a cast in that line according to my understanding. Line 36 is the call of the method updateTextView().
private void updateTextView() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int legalForm = Integer.parseInt(prefs.getString("legal_form", "1"));
boolean industrialTax = prefs.getBoolean("industrial_tax", false);
boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
boolean disbursal = prefs.getBoolean("disbursal", false);
String tmp = prefs.getString("capitalownership", "0"); //this is line 56
int capitalOwnership = Integer.parseInt(tmp);
int estIncome = Integer.parseInt(prefs.getString("est_income", "0"));
}
My preference in the XML-File is the following:
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="#string/capitalownership"
android:inputType="number"
android:key="capitalownership"
android:title="#string/capitalownership" />
I needed I will post the full code and full Error list.
I am relatively new to Android.
Solution
private void updateTextView() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String legalForm = prefs.getString("legal_form", "1");
boolean industrialTax = prefs.getBoolean("industrial_tax", false);
boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
boolean disbursal = prefs.getBoolean("disbursal", false);
String capitalOwnership = prefs.getString("capitalownership", "0");
String estIncome = prefs.getString("est_income", "1");
settingstv.setText(getString(R.string.overview_settings,
legalForm,
Boolean.toString(industrialTax),
Boolean.toString(turnoverTax),
Boolean.toString(disbursal),
capitalOwnership,
estIncome));
try {
if (!compareCurrentWithStoredVersionCode(this, prefs, "storedVersionCode")) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("legal_form", legalForm);
editor.putBoolean("industrial_tax", industrialTax);
editor.putBoolean("turnover_tax", turnoverTax);
editor.putBoolean("disbursal", disbursal);
editor.putString("capitalownership", capitalOwnership);
editor.putString("est_income", estIncome);
editor.commit();
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "updateTextView()", e);
}
}
The first time you've saved capitalownership you probably didn't save it as a String, so when you try to retrieve it, it will retrieve an Integer but you try to cast to String when you do getString and it will get the exception.
String tmp = prefs.getString("capitalownership", "0");
try like this:
int tmp = prefs.getInt("capitalownership", 0);
Besides, you've already set your edit text to input only numbers, so you won't get a String here.
Edit:
Shared Preferences are stored as a Map<String, Object>. As you can see the value of the map is a general Object, if you saved as an Integer you'll need to retrieve as an integer. Ths is quite dynamic, so if you saved one time as an integer and the next time as a String (to the same key) you need to keep track of the type you've saved so you can retrieve it.
If you've saved once as Integer and later save again (in the same key) as a String, when you retrieve it you'll need to use getString(). If you're not sure what's in there you can use the getAll() method to retrieve the entire preferences as a Map<String, Object>, then you can use get("capitalownership") in this map and finally check with instanceof to see what type it is. But this is too cumbersome, you need only to estabilish that you'll save that key(capitalownership) with a certain type and make sure you do that always.
So this is what's happening:
1)You try to retrieve the value associated with that key and Android gives you an Object,
2) Android then tries to cast to the value associated with the method (a String in your case). As the value is actually an Integer that's where the class cast problem comes from.
https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String) :
Returns the preference value if it exists, or defValue. Throws
ClassCastException if there is a preference with this name that is not
a String.
So I'm guessing you have a "capitalownership" preference that has been stored as an Integer
You should not use
int capitalOwnership = Integer.parseInt(tmp);
because you are trying to get an integer as a string
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="#string/capitalownership"
**android:inputType="number"**
android:key="capitalownership"
android:title="#string/capitalownership" />
instead use this
int capitalOwnership = pref.getInt("capitalownership", 0);
also you need to save it like this
pref.putInt("key",value);
Im using SharedPreference on android to store a Set of Strings. It is stored and retrived fine to my knowledge but when the app is restarted some data is lost. Strings are add one by one and before adding them I retrieve the set, add a String and then store it again.
This is how I store it:
Set<String> emptySet = null;
SharedPreferences prefs = getContext().getSharedPreferences(getContext().getString(R.string.pref_disagree_key), Activity.MODE_PRIVATE);
String newIdAgreed = getItem(position).getId();
if (prefs.contains(getContext().getString(R.string.pref_disagree_key))) {
Set<String> updateSet = prefs.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet);
updateSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), updateSet);
editor.commit();
} else {
Set<String> newSet = new HashSet<String>();
newSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), newSet);
editor.commit();
}
And this is how I get it back:
if (prefsDisagree.contains(getContext().getString(R.string.pref_disagree_key))){
disagree_set = new HashSet<String>(prefsDisagree.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet));
for (String item: disagree_set){
//stuff done here
}
}
I saw some similar questions about this topic but none of the answers solved my problem. Any ideas?
The StringSet is not persistent when you are trying to edit it all again after it was saved and therefore newer data that was just added wont get saved when you quit the app and open it again.
It is actually documented: getStringSet
You need to copy first the StringSet and then insert/add data to the copied StringSet:
Set<String> s = new HashSet<String(prefs.getStringSet(
getContext().getString(R.string.pref_disagree_key),
emptySet));
How do you make a variable that can be used across the application. For example, in Swift, you can name it by:
var formattedPrice: String = rowData["date"] as String
defaults.setObject(rowData, forKey: "rowData")
and you can fetch it with:
var variable = defaults.dictionaryForKey("rowData") as? NSDictionary
How can this behavior be mimicked in android studio?
The example you provided looks very similar to SharedPreferences in Android. SharedPreferences allow you to store data and access said data globally within your application. Here is a simple code snippet that shows you how to save and recall an int. You can save the variable as follows:
SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("your_integer_key", yourIntegerValue);
editor.commit();
And then retrieve it anywhere in your application like so:
SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
int myIntegerValue = sharedPreferences.getInt("your_integer_key", -1);
For an app I am developing, I am having the user input some information on one activity, and then on the next, the user will read something, in such that he/she won't be putting any information on it, but on the third activity, I want to display what the user put in the first. Is there a way I can carry that information from the 1st to the 3rd activity without going through the second?
Use sharedPreferences to store that piece of data on the phone. On the 3rd activity, read it and use it.
See it here-
http://developer.android.com/guide/topics/data/data-storage.html#pref
This can be done in many ways !
Why not use Intents to pass the data ?
STEP-1: <Eg:: From Activity1>
Pass the telefone into a new activity with the help of intents
Intent i = new Intent(getApplicationContext(), Activity2.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
STEP-2: <Eg:: From Activity2>
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
STEP-3: <Eg:: From Activity2> pass data again to Activity3
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
Pass the data to Activity3
Intent i = new Intent(getApplicationContext(), Activity3.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
Hope it helps ! ..........Let me know if you need more info
Use SharedPreference. Save in A1 and retrieve in A3.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
I have this method :
private void deleteExam(String i) {
SharedPreferences prefsContatore = getSharedPreferences("esameKey"+i, Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
editorContatore.putString("esameKey"+i, "0");
editorContatore.commit();
}
Go? Can I call recursively "esameKey"+i?
getSharedPreferences access to a file and create if it does not exist. Every time you pass a different i a new file is created. Create it once:
SharedPreferences prefsContatore = getSharedPreferences("mySharedPrefFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
first argument of putString is a key the second paramter is the value you want to store
editorContatore.putString("esameKey"+i, "0");
this way you are putting for every i the value of 0. Is really that what you want?