Android - Make my own layout of Preference - android

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.

Related

editor.remove() in sharedpreferences not removing the key

I have experienced a strange behavior that does not make any sense to me.
I have managed to save a value of temperature in sharedpreferences in a Java Class that is not an activity by doing this:
The method getContextOfApplication() is the one I am using in my Java.Class where i am putting the value of a temperature in a String and storing it in sharedpreferences as "temperature".
This method is declared in my MainActivity like this:
public static Context contextOfApplication;
public static Context getContextOfApplication() {
return contextOfApplication;
}
This method getContextOfApplication(); is the used in all assosiacions with sharedpreferences, in Mainactivity and in my Java.Class
tempParsed = Jobject.get(("temp")) + "";
SharedPreferences tempSettings = getSharedPreferences(getContextOfApplication());
SharedPreferences.Editor tempEdit = tempSettings.edit();
tempEdit.putString("temperature", tempParsed);
tempEdit.apply();
And later I recieve this value of the key "temperature" in my MainActivity like this:
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
String Temp = fetchSettings.getString("temperature", "");
And I can use the stored temperaure with the String Temp.
So far so good.
Later on in my code I wanted to delete this string in that is saved in sharedpreferences with the key "temperature".
Easy I thought...
First I called this code when I wanted to delete the value / values
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
SharedPreferences.Editor editor = fetchSettings.edit();
editor.clear();
editor.apply();
But this code deletes ALL information that is stored, so I obvously didn't want that.
That's why I tried to change this line:
editor.clear();
editor.apply();
To this:
editor.remove("temperature")
editor.apply();
But this didn't work!!
Now you are probably wondering "Are you sure that is what your key is named?"
I added this code to read all entries that were stored in the defaultsharedpreferences:
Map<String, ?> allEntries = fetchSettings.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("mapvalues ", entry.getKey() + ": " + entry.getValue().toString());
}
AND THE LOG SHOWS "temperature:" as the key....
Why is editor.clear(); working but editor.remove("key") is not?
According to the docs you need to call commit for the changes to happen:
editor.remove("temperature").commit();
Solved
You can try this code for remove single preference:
Prefs.remove("my_custom_key");
Don't forget to import library:
import com.pixplicity.easyprefs.library.Prefs;
This code worked for me Beautifully.

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.

how to get the value of json object which i have saved in sharedpreference from one activity to another activity?

This is first activity through which i'm saving data in sharedpreferences...
JSONObject obj = new JSONObject(response);
public static String userid;
userid = obj.getString("userid");
String otp = obj.getString("opt");
SharedPreferences sp=getApplicationContext().getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("userid", userid);
editor.putString("opt", otp.toString());
editor.commit();
and i want the value of userid in second activity...
SharedPreferences sp = getApplicationContext().getSharedPreferences("Sharedprefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");
i want the value of "userid" and "otp" which have been stored in "SharedPrefs" sharedprefs, and i dont want to give any default value for this....
Thanks in Advance :)
If above is your code you should change Sharedprefs in the second Preferences to SharedPrefs.
When you store data in SharedPreferences, make sure that Preference name is spelled correctly. It is case sensitive.
Find the difference between "Sharedprefs" and "SharedPrefs".
Try this way.
SharedPreferences sp = getApplicationContext().getSharedPreferences("SharedPrefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");

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);

Categories

Resources