how to store multiple key value pairs in shared preferences - android

I have username and password field I want to store them using shared preferences.please guide me in storing and retrieving these data using sharedpreferences.
sharedPref=getApplicationContext().getSharedPreferences("sharedf",Context.MODE_PRIVATE);
String secretKey = sharedPref.getString("imei_num", null);
if(null==secretKey){
editor.putString("imei_num",imei_of_the_device);
editor.putString("pin",pinPrimary.getText().toString());
editor.commit();
}

Store in SharedPreferences :
SharedPreferences prefs = getSharedPreferences("sharedf",
Context.MODE_PRIVATE);
prefs.edit().putString("imei_num",imei_of_the_device)
.putString("pin",pinPrimary.getText().toString()).commit();
And retrieve like this :
String imei = prefs.getString("imei_num", "default value");
String pass = prefs.getString("pin", "default value");

You can use prefs.getString("key","default") retrieve value saved for given key if the key is not found it will return default value instead of null

Related

Not able to get String value from SharedPreferences

I save some String data to SharedPreferences but unfortunately i am unable to get the string value from sharedPreferences.
This is my code to save the data to SharedPreferences
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
userPhone = etPhone.getText().toString();
prefs.edit().putString("userPhone", userPhone).apply();
This saves my number perfectly but when i try to retrieve it in the next activity i get this string instead "userPhone"
This is how i retrieve the string value
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
Log.i("number", phoneNumber);
My logs show phoneNumber as a string instead of the value from the user input that i saved to sharedPrefrences.
For storing values into SharedPreferences you are using Editor and method call:
prefs.edit().putString(String key, String value)
And you did it right:
prefs.edit().putString("userPhone", userPhone).apply();
For retrieving data, we are using the same key as we used for storing. In your case, it is "userPhone".
So, you should do it with:
prefs.getString("userPhone", "Some default value");
But, you mixed key with preferences name and you called
prefs.getString(Config.PREF_NAME, "userPhone");
Here is the difference.
You are actually retrieving the value from:
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
But you need to do :
SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = sharedPreferences.getString("userPhone", null);
It should look like this in your second Activity.
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = prefs.getString("userPhone", "defaultValueIfNoPhoneAvailable");
Log.i("number", phoneNumber);
The second parameter of getString is the default value in case it has no mapping for the key.

Android two different SharedPreference types with the same ID

Currently I want to store two different data types as SharedPreference in my android app. Is it possible to store them with the same key-value?
e.g:
int id = 123;
myBoolean = false;
myString = "hello";
SharedPreferences.Editor edit = this.getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
edit.putString(String.valueOf(id), myString);
edit.putBoolean(String.valueOf(id), myBoolean);
because currently, when I try to get the string value I get a ClassCast exception here:
SharedPreferences settings = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String myString = settings.getString(String.valueOf(123), "def");
I get this exception:
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
It is not possible, Shared Preferences is a key value pair (the key is unique). What your code does is replace the previous saved value. So, when you try to get the value you receive a boolean.

How to avoid adding duplicate values in shared preferences in android?

In android, i am adding string values using shared preferences, but i want to compare the value which i am going to add to shared preferences with values which are already stored in shared preferences to avoid adding duplicate values, but i am not getting how to do this?
or is there any alternate method to avoid adding duplicate values in shared preferences?
I am adding string values using following code
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, s);
editor.commit();
In android you cannot really have duplicate value in sharedPreference because every time you change or modify a value on sharedPreference it will replace the previous with the current. So since every instance of it has a single unique key, which mean it will always be unique (in my experience every time i messed up with this keys like giving the same name key for both an Int and boolean for example i end up crashing the app or having some kind of exception)
If im wrong i hope someone else will correct me and provide you with a better answer!
I don't know whether I'm understanding your question quite well or not, but Android's SharedPreferenceshas it's own contains to check if a a key already exists or not.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(NAME)) //It already contains NAME key
On the other hand, if your worries are about a single key's value not to be repeated, just read it before storing the new value and compare themselves, no more.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.getString(NAME, "").equals(s)) {
// It does not have the same value, store 's'
sharedpreferences
.edit();
.putString(NAME, s);
.commit();
}
However, in this particular case I wouldn't perform this verification, just overwrite the value and that's it, as it always gonna be the same.
First get String value from SharedPreferences as oldvalue then compare with newvalue which you want to store. If String not match then save newvalue in SharedPreferences.
Try something like this
String str_newvalue = "new string here";
SharedPreferences sharedpref = this.getSharedPreferences(this.getPackageName(), context.MODE_PRIVATE);
String str_oldvalue = sharedpref.getString("key", "");
if (!str_newvalue.equals(str_oldvalue)) {
sharedpref.edit().putString("key", str_newvalue).commit();
}
Do this
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText.matches(your string))
{
// do nothing
}
else
{
//save your data
}
}

How to store User name and password details in strings.xml

I am developing an app, it has a login page. I need to store the login credentials. Can it be in my strings.xml file? Because I have heard that Strings.xml can not be modified at run time. So where can I store data i.e. User details or application details?
You can store login information in SharedPreference or SqliteDatabase.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", YOUR_USERNAME);
editor.putString("password", YOUR_PASSWORD);
editor.commit();
For retrieving Login information
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String username = prefs.getString("username", null);
String password = prefs.getString("password", null);
If you need more security you can use SQLCipher using SqliteDatabase
Please go through this link.
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getUserName()
{
SharedPreferences sp = getSharedPreferences("userNameAndPassword", 0);
String str = sp.getString("userName","no userName created");
return str;
}
public String getPassword()
{
SharedPreferences sp = getSharedPreferences("userNameAndPassword", 0);
String str = sp.getString("password","no password created");
return str;
}
public void writeToUserNameAndPassword(String userName, String password)
{
SharedPreferences.Editor pref =
getSharedPreferences("userNameAndPassword",0).edit();
pref.putString("userName", userName);
pref.putString("password", password);
pref.commit();
}
You could call them like this:
// their userName if "foo" and their password is "bar"
writeToUserNameAndPassword("foo", "bar");
if (getUserName().equals(inputUserName) && getPassword.equals(inputPassword))
{
// they have the right userName and password
}
else if (getUserName().equals("no userName created")
&& getPassword().equals("no password created"))
{
// these preference Strings for their userName/password have both not been created
}
else if (getUserName().equals("no userName created"))
{
// this preference String for their userName has not been created,
// but the password has been
}
else if (getPassword().equals("no password created"))
{
// this preference String for their password has not been created,
// but the userName has been
}
else
{
// they entered the wrong userName and/or password
}
Some explanation (if needed):
"password" and "userName" are the 'key' Strings in the preference. So you reference those keys to obtain the String you put in there. It is a reference name for the String you put.
"userNameAndPassword" is the preference name. You use the preference name, "userNameAndPassword", to reference the preference you want to access.
"no password created" and "no userName created" are the Strings that the getString method will return if the preference doesn't have a String referenced to by "password" or "userName", meaning that it hasn't been created.
Another way to put it: they are the default values of the reference String. So if nothing has been put their instead, the method will return the default values. You have to set the default values.
So, for example, if no "password" String has been put into the "userNameAndPassword" preference (written to using putString), then the getPassword() method will return "no password created".
As #Armit mentioned before, you can store the data in the SharedPreferences. Just be aware that this gets stored in a simple XML file that can be seen and modified with an editor. You should at least encrypt it or, better, not save it at all. Usually, you log in to a server or site and then save only the return token. You only use the token to connect again and you don't have to save the password in plain text.
In simple words YOU CAN'T STORE OR CHANGE the content of strings.xml
But yes as User #amit said you can
store these values in Shared Preferences
Or You can Use SQLite Database to store what ever you want learn sqlite
For example
for setting the Value
SharedPreferences.Editor prefEditor = getPreferences(MODE_PRIVATE).edit();
prefEditor.putInt(LAUNCH_COUNT, 1); // you can have multiple put (values)
prefEditor.commit();
prefEditor.apply();
For getting the value
SharedPreferences sp = getPreferences(MODE_PRIVATE);
int launchCount = sp.getInt(LAUNCH_COUNT, -1);

Android shared preferences retrieve username and password

Im having trouble with retrieving username and password from android's sharedpreferences. I use this code to save the username and pass
SharedPreferences prefs=getSharedPreferences("File", 0);
SharedPreferences.Editor e= prefs.edit();
e.putString("Email", "example#example.com").putString("Password", "password1");
e.commit();
e.putString("Email", "example_2#example.com").putString("Password", "password2");
e.commit();
String s=prefs.getString("Email","not found");
But i dont know how to retrieve information for user to log in. Can anybody help me figure out
Create Share Preference:
SharedPreferences sp=getSharedPreferences("Login", 0);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString("Unm",Value );
Ed.putString("Psw",Value);
Ed.commit();
Get Value from Share preference:
SharedPreferences sp1=this.getSharedPreferences("Login",null);
String unm=sp1.getString("Unm", null);
String pass = sp1.getString("Psw", null);
You need to give different keys for different values, otherwise the second email will erase the first one. See shared preferences as a persistent hashmap :
//keep constants, don't use their values. A constant has more meaning
SharedPreferences prefs=getSharedPreferences("File", MODE_PRIVATE );
SharedPreferences.Editor e= prefs.edit();
//keys should be constants as well, or derived from a constant prefix in a loop.
e.putString("Email1", "example#example.com").putString("Password1", "password1");
e.putString("Email2", "example_2#example.com").putString("Password2", "password2");
//commit once, not twice
e.commit();
//not found should be a constant in a xml resource file
String mail1=prefs.getString("Email1","not found");
String mail2=prefs.getString("Email2","not found");

Categories

Resources