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
Related
can I save strings to my sharedpreference without using an editText. Using an edit text this is the format of putting string to the shared preference right?
editor.putString("username", etUsername.getText().toString());
I want to happen is to get the users ID from the db for it to be saved on the sharedpreference.
editor.putString("userID", *******);
what should I put there? Thanks. I don't know how to do it.
And this is my db for the users.
myDB
editor.putString("userID", parameter);
yes, in second parameter you can save your sting whatever your want.
You're doing it right.
String stringValue = "BobSmith";
editor.putString("stringKey", stringValue);
This can be done like this:
String valueToBeSaved = etUsername.getText().toString();
editor.putString("userID", valueToBeSaved);
editor.apply();
DatabaseHelper myDatabaseHelper = new DatabaseHelper(Activity.this);
myDatabaseHelper.openDataBase();
String userId = myDatabaseHelper.getYourData(); //this is the method to query user UserId
myDatabaseHelper.close();
//now save userId in shared preferences
String valueToBeSaved = etUsername.getText().toString();
editor.putString("userID", userId);
editor.apply();
}
I hope youe are searching for this. If any doubts let me know.
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
}
}
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);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my application I got user info in shared pref file. When user enter their details on the log in page, I want only users whose info is in shared pref file to log in. How can I do that?
You can use your apps shared preferences. The prefs can be accessed anytime using the key you set for these prefs.
static final String KEY_USERNAME = "username";
static final String KEY_PASSWORD = "password";
if (saveLogInDetail) { //save username and pw to prefs
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = prefs.edit();
ed.putString(KEY_USERNAME, theUsername);
ed.putString(KEY_PASSWORD, thePW);
ed.commit();
}
To access the information or check the valid username and password use this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String storedUsername = prefs.getString(KEY_USERNAME, "Default Value if not found");
String storedPassword = prefs.getString(KEY_PASSWORD, ""); //return nothing if no pass saved
Store your login data in sharedpreferences:
String username="dipali";
String pass="1111";
SharedPreferences.Editor editor = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE).edit();
editor.putString(
"username",
user);
editor.commit();
SharedPreferences.Editor editor = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE).edit();
editor.putString(
"pass",
pass);
editor.commit();
get shared prefences data:
SharedPreferences shar = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE);
String username=shar.getString("username","");
String pass=shar.getString("pass","");
you should use SQlite Database instead of using share preference. Once you set up database then insert user credentials to database if user is a not register. And in your case check if current user is in database if exits authenticate him other wise you can force him to register to application. You can see sqlite in detail here http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
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