I am checking all these at splashscreen activity,
So I am giving this,
SharedPreferences spf = getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe = spf.edit();
String name = spf.getString("name","");
String id = spf.getString("id","");
String class = spf.getString("class","");
String roll = spf.getString("roll","");
spe.commit();
if((spe != null) && (name != null) && (id != null) && (class != null) && (roll != null)){
Intent i = new Intent(Startpage.this,Welcome.class);
startActivity(i);
Startpage.this.finish();
}
else{
Intent i = new Intent(Startpage.this,MainActivity.class);
startActivity(i);
Startpage.this.finish();
}
when I open app startup page directly moves to welcome page,
but I want to move splashscreen page to MainActivity when there is no values saved in shared-preferences
I followed this to get shared-preference values
can any one suggest me how to give condition in this kind
spf.getString("name","");
return as default value a empty string.
Idea:
why not use
spf.contains("name")
that return true or false?
Alternatively you can check if string is empty or null with TextUtils.isEmpty()
method.
String name = spf.getString("name","");
This method creates a shared pref if it doesn't exist already with the default value as the second argument. So in your case, shared pref are saved with empty string as value when user visited the app for first time.
Just change your default value to null since your checks are on null value and it will work -
String name = spf.getString("name",null);
you are putting null check on the string but while reading from the shared preferences you are setting them to empty string if the value is not found in the shared prefs. change your checks to String.isEmpty() in your if condition.
because null and ""are different,
You should use android.text.TextUtils.isEmpty(CharSequence str)instead of str != null
Another way is :
String name = spf.getString("name",null); ,and then like if (Str != null)
For me,i always usee the first way i said to determine whether String is empty.
Hope it helps you :)
Related
i am retrieving all SharedPreferences inside my app like this:
getCollection() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getInt("collectionCount") == null) {
clearCollection();
} else {
collectionCount = prefs.getInt("collectionCount")!;
url = prefs.getStringList("collectionUrl")!.reversed.toList();
method = prefs.getStringList("collectionMethod")!.reversed.toList();
headers = prefs.getStringList("collectionHeaders")!.reversed.toList();
body = prefs.getStringList("collectionBody")!.reversed.toList();
name = prefs.getStringList("collectionName")!.reversed.toList();
syntax = prefs.getStringList("collectionSyntax")!.reversed.toList();
}
}
Is there a way to order the output by the name (collectionName) field in alphabetic order?
Instead of using reversed try with sort function.
Here some info about sort function (i think that language is dart): Sort a list of objects in Flutter (Dart) by property value
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.
SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
urlfoto = sharedPrefNew.getString("fotonew", "");
if(urlfoto!= null && !urlfoto.equals(""))
{
...
}
else {
System.out.println("boş");
...
}
You already declared default value of SharedPreference on Code.
urlfoto = sharedPrefNew.getString("fotonew", "");
This means if "fotonew" is empty or null sharedPrefNew returns a value ""
this line:
sharedPrefNew.getString("fotonew", "")
is responsible for taking value from shared pref. First parameter is a key, second one is a default value that will be returned if key is not found.
In your case, if there is no object stored for key "fotoNew" an empty string will be returned.
You can return null :
sharedPrefNew.getString("fotonew", null);
Hope that helps.
Check below code
if (sharedPrefNew.getString("fotonew", "") != null && !sharedPrefNew.getString("fotonew", "").isEmpty()){
//your code here
}
I need to use SharedPreference for saving login, password and a other string in my application, but i don't want to use the default layout's preference.
I have already read the documentation of SharedPref : http://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs
But.. hum.
I've create a class named preferences_dashboard.
In this class, if a checkbow is checked, i backup login etc, and if the checkbox is not checked, i delete the backup.
There is my code :
public void saveID(View v) {
// strMessage is the message with appears when clicking on Checkbox
String strMessage = "";
CheckBox chkBoxSaveID;
chkBoxSaveID = (CheckBox) findViewById(R.id.preferencecheckBoxSaveID);
boolean chkBoxSaveIDState = chkBoxSaveID.isChecked();
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); // Put the values from the UI
if (chkBoxSaveID.isChecked()) {
// Backup LOGIN
String userLogin ="Administrator2";
String userPassword = "password2";
String userDomain = "12";
editor.putString("KEY_USER_LOGIN", userLogin); // Storing string
editor.putString("KEY_USER_PASSWORD", userPassword); // Storing string
editor.putString("KEY_USER_DOMAIN", userDomain); // Storing string
editor.putBoolean("stateChkBoxMemorizeID", chkBoxSaveIDState); // value to store
editor.commit(); // commit changes
strMessage += "ID memorized" + "KEY_USER_DOMAIN" + userPassword + userDomain;
showTextNotification(strMessage);
} else {
// No backup LOGIN
editor.remove("KEY_USER_LOGIN"); // will delete key name
editor.remove("KEY_USER_PASSWORD");
editor.remove("KEY_USER_DOMAIN");
editor.putBoolean("stateChkBoxMemorizeID", chkBoxSaveIDState); // value to store
editor.commit(); // commit changes
strMessage += "Login is not memorized ";
showTextNotification(strMessage);
}
} // end saveID
I think i don't really understand how use SharedPreferences.
String Login/Pass/Domain are fixed for the test. After, i will recup variables on a other activity.
My question :
Where these variables will be backup ? In data/date/nameappli/xml generated ? Or in the defaultSharedPreference ?
What i have missed ? :(
Thanks for the help.
Instead use :
SharedPreferences sharedPreferences = getSharedPreferences("customSharedPrefs", Context.MODE_PRIVATE);
In this way, you have a seperate SharedPreferences to store the information you want. And you can name it anything. Just pass the name as a string like here I used "customSharedPrefs".
Thus, you can create multiple SharedPreferences with different names.
public void buttonClick(View v)
{
EditText sd = (EditText)findViewById(R.id.sd);
EditText desc = (EditText)findViewById(R.id.description);
Spinner type = (Spinner)findViewById(R.id.type);
Spinner priority = (Spinner)findViewById(R.id.priority);
Set<String> set = new HashSet();
if(!validate(sd))
sd.setError("This field cannot be empty");
else if(!validate(desc))
desc.setError("This field cannot be empty");
else
{
set.add(type.getSelectedItem().toString());
set.add(priority.getSelectedItem().toString());
set.add(desc.getText().toString());
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(sd.getText().toString(),set);
editor.commit();
Log.d("MyTag",pref.getAll().toString());
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
private boolean validate(EditText t1)
{
if(t1.getText().length()==0)
return false;
else
return true;
}
Here in the above code, I am storing the details in the SharedPreferences with StringSet. The key is sd string and the values are desc, type and `priority'. I created a Set and put the key and the corresponding values in the set. How do I fetch the values for a given key?
The method pref.getStringSet(key, Set<String>) expects both key and the values. The key value is known but what should be put in the second argument? Tried null but it expects a type of Set.
The second parameter in pref.getStringSet(key, Set<String>) is a default value in case the preference has never been set before.
Check the documentation:
Parameters
key The name of the preference to retrieve.
defValues Values to return if this preference does not exist.
So if it has already been set, the previously assigned value is returned. Otherwise defValues is returned.
You can go ahead and put null there. The following compiles and works for me:
HashSet<String> hashSet = hashSet = (HashSet<String>) sp.getStringSet("names", null);
The second value is the default value. If Lint gives you an error when you put null, just tell Lint to ignore that error.
The second argument is a default value, if the shared preference you try to get doesn't exist or, you put a wrong name as first argument it will be set to the default value passed as second argument.
The key value is a label wich you will use to get that specific shared preference, for example:
editor.putString("name_of_your_preference", value_of_preference);
and then you could retrieve that string with:
pref.getString("name_of_your_preference", default_value);
you could use NULL only as default value
I save a string set in the shared preferences, if I read it out it's ok. I start other activities, go back and read it again, it's ok. If I close the application, and start it again, I get the set, but with only 1 item instead of 4. It happens all the time. Is there a known issue? What could I do wrong?
In a class, what is created in the application's oncreate method I have a SharedPreferences and a SharePreferences.Editor variable. I use them in the save and load methods.
public void saveFeedback(FeedbackItem feedbackItem) {
checkSp();
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
feedbackSet.add(json.toString());
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);
ed.commit();
}
public Set<String> getFeedbacksSet(){
checkSp();
Set<String> ret = sp.getStringSet(CoreSetup.KEY_FEEDBACK, null);
return ret;
}
private void checkSp(){
if(this.sp == null)
this.sp = applicationContext.getSharedPreferences(applicationContext.getPackageName(), Context.MODE_PRIVATE);
if(this.ed == null)
this.ed = this.sp.edit();
}
I just can't understand how could it happen, to store perfectly all items while the app is running, then after a restart not all items are in the set. And I think if all items are removed it could be more acceptable than some items are gone, and one item is still there. Is there an explanation?
Based on your question, you should call commit only after 4 items have been added to the set.
In your code, you are calling commit for each feedback which will overwrite the previous feedback.
Update:
http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String, java.util.Set)
Note that you must not 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.
This is exactly what you are doing
This "problem" is documented on SharedPreferences.getStringSet().
getStringSet() returns a reference of the stored HashSet object inside SharedPreferences. When you add elements to this object, they are added in fact inside SharedPreferences.
The workaround is making a copy of the returned Set and putting the new Set into SharedPreferences. I tested it and it works.
In Kotlin, that would be
val setFromSharedPreferences = sharedPreferences.getStringSet("key", mutableSetOf())
val copyOfSet = setFromSharedPreferences.toMutableSet()
copyOfSet.add(addedString)
val editor = sharedPreferences.edit()
editor.putStringSet("key", copyOfSet)
editor.apply() // or commit() if really needed
Try to create Copy of your set, and than you can save it in same prefs:
private Set<String> _setFromPrefs;
public void GetSetFromPrefs()
{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
Set<String> someSets = sharedPref.getStringSet("some_sets", new HashSet<String>() );
_setFromPrefs = new HashSet<>(someSets); // THIS LINE CREATE A COPY
}
public void SaveSetsInPrefs()
{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("some_sets", _setFromPrefs);
editor.commit();
}
Ran into this same problem. Solved it by clearing the editor after instantiating and before committing.
sPrefs = PreferenceManager.getDefaultSharedPreferences(context);
sFavList = sPrefs.getStringSet(context.getResources().getString(R.string.pref_fav_key), null);
sEditor = sPrefs.edit();
sEditor.clear(); // added clear, now Set data persists as expected
if (sFavList == null) sFavList = new HashSet<>();
sFavList.add(title);
sEditor.putStringSet(context.getResources().getString(R.string.pref_fav_key), sFavList).apply();
I tried creating a copy as others suggested, but that didn't work for me.
Found this solution here.
According to the document, the String Set in SharedPreferences should treated as immutable, things go south when trying to modify it. A work around would be:
Get the existing set, make a copy of it, update the copy and then save it back to the shared preferences like it was a new set.
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
//make a copy of the set, update the copy and save the copy
Set<String> newFeedbackSet = new HashSet<String>();
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
newFeedbackSet.add(json.toString());
newFeedbackSet.addAll(feedbackSet);
ed.putStringSet(CoreSetup.KEY_FEEDBACK, newFeedbackSet);
ed.commit();
public void saveFeedback(FeedbackItem feedbackItem) {
checkSp();
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
feedbackSet.add(json.toString());
ed.putStringSet(CoreSetup.KEY_FEEDBACK, null);
ed.commit();
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);
ed.commit();
}
To save string in sharedprefernces
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("text", mSaved.getText().toString());
editor.commit();
To retrieve data from shared preference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("text", null);