when we want to get value of a key we should do something like this.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
in getString document wrote.
/**
* Retrieve a set of String values from the preferences.
*
* <p>Note that you <em>must not</em> modify the set instance returned
* by this call. The consistency of the stored data is not guaranteed
* if you do, nor is your ability to modify the instance at all.
*
* #param key The name of the preference to retrieve.
* **#param defValues Values to return if this preference does not** exist.
*
* #return Returns the preference values if they exist, or defValues.
* Throws ClassCastException if there is a preference with this name
* that is not a Set.
*
* #throws ClassCastException
*/
now i have a question why default value argument must exist!?
Because the preference may not have been saved yet. It's easier to deal with this than to write:
String value;
if (sharedPreferences.contains(PREFS_KEY)) {
value = sharedPreferences.getString(PREFS_KEY);
} else {
value = "defaultValue";
}
The answer is in the documentation. What if you call
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
before saving any value? It will have to return null, which in turn can create problems like NullPointerException. So, default value is used as a precaution.
Related
I have 3 columns in my Parse class, FOOD1, FOOD2 and FOOD3.
it is optional for the user if they choose 0,1,2 or 3 Foods they like, i save the foods in these columns. This process will be repeated.
For every loop i want to set all these fields on null/undefined so i can simply see if they choose something after selection.
But when one of the fields eg. FOOD1 is filled in the database, i cant clear the value of it.
i tried:
final ParseQuery queryusername = ParseQuery.getQuery("Usernames");
queryusername.whereContains("names",db.getUsername());
try {
ParseObject p = queryusername.getFirst();
System.out.println("parseobject:"+p);
//make fields empty
p.put("Food1",null); //Error
p.put("Food2",null);
p.put("Food3",null);
}catch(){}
the error is:
java.lang.IllegalArgumentException: value may not be null.
how can i clear the field?
Parse object provides remove(). Pass it the key to remove, e.g.
p.remove("Food1");
p.remove("Food2");
p.remove("Food3");
It seems that Parse SDK has checks for null.
From the source
/**
* Add a key-value pair to this object. It is recommended to name keys in
* <code>camelCaseLikeThis</code>.
*
* #param key
* Keys must be alphanumerical plus underscore, and start with a letter.
* #param value
* Values may be numerical, {#link String}, {#link JSONObject}, {#link JSONArray},
* {#link JSONObject#NULL}, or other {#code ParseObject}s. value may not be {#code null}.
*/
Why do you need to set it to NULL? You can always use empty String or some constant integer or finally JSONObject.NULL.
Or use p.remove as in the answer by #danh
The answer of https://stackoverflow.com/users/294949/danh works. You must save the object:
p.remove("Food1");
p.remove("Food2");
p.remove("Food3");
try {
p.save();
}
catch (ParseException e) {
}
This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
I'm new in android,I want to know is possible to store boolean and integer values in same shared preference.
/**
* Save value to shared preference.
*
* #param key On which key you want to save the value.
* #param value The value which needs to be saved.
* #param context the context
* #description To save the value to a preference file on the specified key.
*/
public synchronized void saveValue(String key, long value, Context context) {
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor saveValue = prefs.edit();
saveValue.putLong(key, value);
saveValue.apply();
}
/**
* Gets value from shared preference.
*
* #param key The key from you want to get the value.
* #param defaultValue Default value, if nothing is found on that key.
* #param context the context
* #return the value from shared preference
* #description To get the value from a preference file on the specified
* key.
*/
public synchronized String getValue(String key, String defaultValue, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(key, defaultValue);
}
Although if you want to save POJO's in shared preferences go for GSON
JSONArray.getString(1); where ["name",null] is the json array, throws a JSONArray[1] not a string exception only when proguard is enabled.
Am I missing something in my proguard rules?
Did you try these methods:
/**
* Returns the value at {#code index} if it exists, coercing it if
* necessary. Returns the empty string if no such value exists.
*/
public String optString(int index)
or
/**
* Returns the value at {#code index} if it exists, coercing it if
* necessary. Returns {#code fallback} if no such value exists.
*/
public String optString(int index, String fallback)
Seem like does not return null for String
In my app, I have flashcard objects that the user creates themselves. Users can create as many flashcards as they want, but when they exit the app and return they need to be able to see the flashcards that they previously created and be able to delete them. I have it set up so that they can create/delete, but if they exit the app they will all delete automatically. What is the best way to save the information for a flashcard? It has at least 3 strings currently, the title, the front and the back.
I looked at a few, but am not sure how I would include all three strings in the saving options that are on the android developer site.
For example shared preferences, looks like you can only save certain settings, but it allows the user to change those settings.
The internal/external storage, although very different throw up the same problem, how to have unlimited number of objects and especially how to save all three strings separately.
This is the internal storage is shown below.
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
I don't see how you can save multiple number of objects or 3 different strings.
Does anyone see a solution to my problem?
SharedPreferences seem like the simplest way for you to achieve it, and I think you've misunderstood their usage, or confused the name with a 'Preferences' screen, as you can use the SharedPreferences methods to save anything (well, any basic datatype) persistently.
For example, I use it to save my app's JSON data (which might be a decent way for you to go in terms of saving you users' flashcards in a JSONArray).
/**
* Retrieves data from sharedpreferences
* #param c the application context
* #param pref the preference to be retrieved
* #return the stored JSON-formatted String containing the data
*/
public static String getStoredJSONData(Context c, String pref) {
if (c != null) {
SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
return sPrefs.getString(pref, null);
}
return null;
}
/**
* Stores the most recent data into sharedpreferences
* #param c the application context
* #param pref the preference to be stored
* #param policyData the data to be stored
*/
public static void setStoredJSONData(Context c, String pref, String policyData) {
if (c != null) {
SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString(pref, policyData);
editor.commit();
}
}
Where the string 'pref' is a tag used to refer to that specific piece of data, so for example: "taylor.matt.data1" would refer to a piece of data and could be used to retrieve or store it from SharedPreferences
Is there any kind of contact variable that is persistent between ROM flashes or factory resets ? I created an app that looks for the contacts id but apparently that changes when there is a sync from a factory reset or new ROM (and between devices). I need to store a unique identifier. Please help. Thank you.
If you are talking about sim data maybe you might figure out something. But if you are talking about an unique identifier the only efficient way i know is generating a UUID key and storing it locally and externally, as suggested by Reto Meier at Google I/O 2011. Here is my snippet (Don't mind my javadoc style ^^);
/**
* This is just a local solution. For world-wide usage,
* backup on a cloud is encouraged.
*
* #reference Reto Meier - Google I/O 2011
*
* #param context for accessing related shared preferences file
* #return unique id
*/
public synchronized static String getUniqueId(Context context)
{
String uniqueID;
//Open shared preferences file for PREF_UNIQUE_ID
SharedPreferences sharedPrefs = context.getSharedPreferences(PREF_UNIQUE_ID, Context.MODE_PRIVATE);
//Fetch id, if any.
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
//If no id saved into shared preferences before generate new one
if(uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
}
return uniqueID;
}