In case the user login to app and then switch to other app without logout, how we manage the remember of the credential so once the user back to the previous application he don't need to type credential details again (user/pass)- (Please provide answer with theory also)
Define some statics to store the preference file name and the keys you're going to use:
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
You'd then save the username and password as follows:
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
So you would retrieve them like this:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username == null || password == null) {
//Prompt for username and password
}
Alternatively, if you don't want to name a preferences file you can just use the default:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
You can use applicationPreference for storing the username and password. Google for it, you can easily get the code for it. But for security reason, always try to save such information in encrypted form. And while retrieving info from applicationPrefernces, you have to decrypt it. here is link http://www.androidsnippets.com/encryptdecrypt-strings
Related
I want to cache the Username of the current user logged in, because I don't want to reload the username string everytime the activity refreshes.
What methods/startegies can I use to do that?
There are lots of solutions to fix your issue :
you can save the user name into sharedpref or into database
As an advanced solution i would like to advice you to read about the Singleton design patter : the idea is to create a class and to make a public one Single instance from it (you can do when the user login) and then every class in your project can get access to it. please take a look here
Concerning the easiest way to solve your issue i believe that shared preferences can do the job
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "abc");
editor.commit();
And to retrieve your data you can proceed like following :
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.
}
As one of the tag in question is marked "Firebase", I will assume you are using Firebase as your back-end and Firebase Auth for authenticating the user.
Firebase allows you to get the Display Name, Email-id (username) and users profile picture using "FirebaseUser".
To retrieve the user associated information use the below code:
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseAuth user_token = FirebaseAuth.getInstance();
FirebaseUser currentUser = user_token.getCurrentUser();
currentUser.getDisplayName(); //Display Name
currentUser.getEmail(); //Username
currentUser.getPhotoUrl(); //PhotoURL if the user used any social media for auth
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.
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.
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);
I am using following source https://github.com/liveservices/LiveSDK-for-Android.
Do someone know how to get shared preferences after the LiveAuthClient process. I have to get
REFRESH_TOKEN_KEY and COOKIE_DELIMITER from the sharedprefences file and clear it after saving it in a database. The aim is to save this to values in a database to login with multiple skydrive accounts.
Any ideas would be helpful. Thank you.
If Someone wants to know use:
/** Name of the preference file */
public static final String FILE_NAME = "com.microsoft.live";
public static final String COOKIES_KEY = "cookies";
public static final String REFRESH_TOKEN_KEY = "refresh_token";
SharedPreferences preferences = getSharedPreferences(SDriveConstants.FILE_NAME, Context.MODE_PRIVATE);
String refresh_tkn_key = preferences.getString(SDriveConstants.REFRESH_TOKEN_KEY, "");
String cookies_key = preferences.getString(SDriveConstants.COOKIES_KEY, "");