When I click on the 'remember me' checkbox, based on the codes it will save the username and password by sharepreferences. However, when I exit my application and go back, the username and password will disappear.
How do I save the username and password between sessions?
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
// save username & password
SharedPreferences mySharedPreferences = getSharedPreferences(
"PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("UserName",
String.valueOf(txtLogin.getText().toString()));
editor.putString("Password",
String.valueOf(txtPassword.getText().toString()));
editor.commit();
}
Same as you have put username and password strings inside the shared preference, you can retrieve the same by doing as below:
SharedPreferences settings = getSharedPreferences("PREFS",0);
settings.getString("UserName", "");
settings.getString("user", "");
But i think for implementing remember me functionality, just put a boolean flag whenever the login is successful:
editor.putBoolean("login",true);
and retrieve whenever app is re-started next time:
settings.getBoolean("login", false);
When you exit the app and go back, the onResume() method will be called. It's the place where you should put Paresh Mayani's codes to retrieve the username and password. Check here to understand the lifecycle of an activity in Android.
I think the problem is with the Activity.MODE_PRIVATE flag use instead getSharedPreferences("PREFS", MODE_WORLD_WRITEABLE) flag.
Related
My first application in android studio and i want to do this:
Description:
username:username (TextBox)
password:password (TextBox)
Keep me logged in -->CheckBox
LOGIN -->BUTTON
The first time where the user enters your username and password and click to Keep me logged in the application must be remember the username and password without the user writes again in the second time.
Could anyone give me some idea how this implement in android, I found many examples but nothing work.
You could use SharedPreferences to remember the user preference. Here it is a boolean.
SharedPreferences prefs = getDefaultSharedPreferences(this);
boolean keepLoggedIn = prefs.getBoolean(KEY_KEEP_LOGGED_IN, false);
//After user makes the selection on the checkbox,
SharedPreferences.Editor editor = getDefaultSharedPreferences(this).edit();
editor.putBoolean(KEY_KEEP_LOGGED_IN, true);
editor.commit();
I did something very similar to this recently
First, make sure to initialize your fields in question
AutoCompleteTextView mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
EditText mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
Set your onClick event:
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
In order for the user password to be remembered, you have to save them somewhere. I stored them in shared preferences, but you can use a more secure method depending on your application or even encrypt before storing them http://developer.android.com/guide/topics/data/data-storage.html#pref
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Put the strings in the editor
editor.putString(getString(R.string.userAccount), email);
editor.putString(getString(R.string.password), password);
Now in onCreate or your other favorite android start method (depending on if you're using a fragment or activity), retrieve them
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
//Retrive the values
sharedPref.getString(getString(R.string.userAccount), "")
sharedPref.getString(getString(R.string.password), "")
Currently I have an EditText field which requires user to input their address. First time user has to input the address. How do I auto complete it when the same user use the app again ?
Use SharedPreferences. Here is a complete example
Use SharedPreferences
Call this to save:
SharedPreferences.Editor prefsEditor = getPreferences(MODE_PRIVATE).edit();
prefsEditor.putString("address", address.getText().toString());
prefsEditor.apply();
Call this to load:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
address.setText(mPrefs.getString("address", ""));
Your going to want to add some further code to this such as:
Null checks
I have a few data I saved in SharedPreference. WHen a button is clicked, the user is logged out and the sharedPreference is cleared by calling pref.clear() ad pref.commit(). When a user tries to log back in, the editor is called to commit() but it wouldn't save the new values. Any suggestions why shared preference is not saving after clearing is done?
Clearing part:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor sa = prefs.edit();
sa.clear();
sa.commit();
re-adding part:
editor.putString("bucket", bucket);
editor.putString("profileid", profileid);
editor.putString("username", user);
editor.putString("password", pass);
editor.commit();
CLOSED: answer in the bottom but for anyone else that is looking for an answer, i accepted the answer
how are you initializing editor (whitch I asume is SharedPreferences.Editor). I use the following to get editor.
SharedPreferences settings = getActivity().getSharedPreferences("a_string", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
I do this the same way for clearing and saving my data.
pleas post more information if this dose not help.
Actually my fault, there was a typo while I was initiation my preferences. Sorry folks!
Let me show you a working example of how to add/read/remove data from SharedPeferences.In your Activity for adding some data into SharedPreferences
SharedPreferences prefs = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("bucket", bucket);
editor.putString("profileid", profileid);
editor.putString("username", user);
editor.putString("password", pass);
editor.commit();
You would want to do the above when is user is logged in successfully.Now when the user logout, inside your onClickListener for logout Button
SharedPreferences settings = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
So in your Activity's code you should check if SharedPreferences values are already set.If they are set, then you can redirect user to the home screen without having to login again.
I'm new to android and java. I tried SharedPreferences to manage session. Once I login into screen I writing below code.
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", true);
editor.commit();
When I closed the app and started again, it directly going to home screen without asking the credentials.
I dont know where to write these below lines:
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
I want to clear the SharedPreferences even if the app closed directly. I tried with finalize but it didn't worked.
EDIT:
I add below code to my file. It is working but giving error.
code:
protected void onStop() {
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", false);
editor.commit();
}
Error:
android.app.SuperNotCalledException: Activity {com.ec.testtab/com.ec.testtab.Tabs} did not call through to super.onStop()
Better to set prefs to false at your app closed. and when you come back again you just need to check this prefs value true or false.
false--- means not login
true---- means logined
I have handeled such things inside these two methods of activity they will be called in your case too so give a try:
#Override
protected void onResume() {
super.onResume();
// Start Logging
}
#Override
protected void onPause() {
super.onPause();
// End Logging
}
If you don't want to store shared preferences while your app is getting closed, you should clear your shared preferences every time your app is getting started, so that no previous shared preferences will be there while doing your app's further processes.
Once user logged-in into app with valid credentials then only changed share preferences login value to true.
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", true);
editor.commit();
And every time on Oncreate just check "login" value to determine whether user is already logged-in or not.
You can add this lines of code
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", false);
editor.commit();
when your app starts before fetching the username and password from the preferences. So that every time you start the app it will show login page.
Sharedpreferences is used for persistent storage, if u don't need store information for next launcher, use public static boolean isLogin maybe an easy way:
public static boolean sIsLogin = false;
...
if(doLogin()){
sIsLogin = true;
}
...
When u closed the app and started again, sIsLogin is false.
I am new in android development.
I've an activity in which I'm taking user name and password.and I'm passing those values to a web service which returns a key as a response.i have one toggle button in my activity. now if the user checks the toggle button that means he want to keep logged in and the user should be redirected to next activity when he next time log-in.
If toggle button is checked I'm storing user name, password and key in shared preference.
but I'm not getting how to retrieve those details next time(i.e when user next time log-in)
userDetails = this.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("username", txtUname.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
Toast.makeText(this, "Login details are saved..", 3000).show();
this way you can fetch preference
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
and check for login this way
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
try like this
best of luck
try this for store value in sharePreferences..
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);
/////////////////////////////////////////
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
Based on the Checkbox add a sharedPreferences Boolean value when the user checks/unchecks on keep logged in. Then as you call onCreate of Login activity you need to check this and call the next activity if the boolean value is true.
Avoid storing the user password.
For each user, consider storing:
the user id
a random seed unique to this user
a hash of the seeded password.
The user will need to reenter his password, then you can add the stored seed to the entered password and apply the hash algorithm X times to the seeded password. Then compare the hash to the stored hash.
Then he can encrypt the password and store it in sharedpreferences whenever he needs the password he can get that encrypted password from the sharedpreferences and decrypt it.
Try this https://prashantsolanki3.github.io/Secure-Pref-Manager/ for saving and retrieving shared preferences securely and with ease.
The keys and values are automatically encrypted.
Save:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();
Retrieve:
String userName = SecurePrefManager.with(this)
.get("user_name")
.defaultValue("unknown")
.go();
Hope this helps!