Iam saving my user login details into my SharedPreferences file. The problem is when I try to clear the ShredPreferences, the details dont clear. When the next user logs in his details are not shown.
Here is my code:-
Save.java
sessionManager.createLoginSession(username, deviceId, name );
SessionManagement.java
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "UserDetails";
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String emailId, String deviceid,String usersname)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putBoolean(KEY_DEVICEREGISTERED, true);
editor.putString(KEY_EMAILID, emailId);
editor.putString(KEY_DEVICEiD, deviceid);
editor.putString(KEY_USERSNAME, usersname);
// commit changes
editor.commit();
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails()
{
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
user.put(KEY_DEVICEiD, pref.getString(KEY_DEVICEiD, null));
user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, null));
// return user
return user;
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin()
{
// Check login status
if(!this.isLoggedIn())
{
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
// This function clears all session data and redirect the user to LoginActivity
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
//editor.clear();
editor.remove(KEY_DEVICEiD);
editor.remove(KEY_EMAILID);
editor.remove(KEY_USERSNAME);
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
Logout.java
SessionManagement session = new SessionManagement(getApplicationContext());
session.logoutUser();
finish();
i'm using this structure
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.putBoolean(IS_LOGIN, false);
editor.putString(KEY_TOKEN, "");
editor.putString(KEY_EMAIL, "");
editor.commit();
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
Try the above code.Hope it will work.
Related
I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..
In oncreate the onclicklistner that opens next activity if credentials are good
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
load_data();
}
}
});
Code of shared pref
private void savePreferences() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.commit();
}
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
// Get value
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
}
What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()
if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.
so your code may look like this:
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
//you can start the 2nd activity directly here
//Intent intent = new Intent (...)
//startActivity(intent);
//finish();
//OR
//load data into edittexts and programatically click the login button
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
//here it will click the button as if the user did it.
btnLogin.performClick();
}//contains
}
Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
CheckLogin();
...
}
private void CheckLogin(){
if(session.checkLogin()){finish();}
}
SessionManager.java
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);
So it should be like
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.putBoolean("hasLoggedin", true);
editor.commit();
then check in Oncreate method like
boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
if (hasLoggedin) {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
I have a problem in my code , a method always return false even if i insert true
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
even if I add true before checking ,this code it will return false
* */
public void checkLogin(){
// Check login status
editor.putBoolean("login", true);// even if add true it will return false
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
what I am trying to do is having a register buttom in the action bar once click it will give the user register activity . then he will insert user name and password and returns him to mainactivity. if he click register button again it should send him to another activity because his login
in my code even if he is login it is sending him to register activity because the false return that i explained above the below is my code
sessionmanager
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
// Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
//SharedPreferences.Editor editor;
SharedPreferences.Editor editor;
// Constructor
public SessionManager(Context context){
this._context = context;
// pref = PreferenceManager.getDefaultSharedPreferences(context);
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
System.out.println(pref.getBoolean("login", false));
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything\
* */
public void checkLogin(){
// Check login status
// editor.putBoolean("login", true);
editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
else {
Intent i = new Intent(_context, UserProfile.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
}
mainactivity part where I am calling the register.java
case R.id.ic_register:
// session= GlobalContext.getInstance().getSession();
// session.checkLogin();
session.checkLogin();
Toast.makeText(this, "Create a new account please", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(this, Register.class);
//startActivity(intent);
return true;
register
SessionManager session;
Button btnLogin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final AlertDialogManager alert = new AlertDialogManager();
session= GlobalContext.getInstance().getSession();
usernam = (EditText) findViewById(R.id.username);
passw = (EditText) findViewById(R.id.password);
email = (EditText) findViewById(R.id.email);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
btnLogin = (Button) findViewById(R.id.login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = usernam.getText().toString();
String password = passw.getText().toString();
// Check if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with sample data
// username = test
// password = test
if(username.equals("test") && password.equals("test")){
// Creating user login session
// For testing i am stroing name, email as follow
// Use user real data
session.createLoginSession("test", "test");
// Staring MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}else{
// username / password doesn't match
alert.showAlertDialog(Register.this, "Login failed..", "Username/Password is incorrect", false);
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
alert.showAlertDialog(Register.this, "Login failed..", "Please enter username and password", false);
}
}
});
}
you need to perform commit, in order to save value in preference
so just after adding anything write editor.commit(), please check updated method
public void checkLogin(){
// Check login status
editor.putBoolean("login", true);// even if add true it will return false
editor.commit();
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
I am using shared preference. Why this method is always returning false ?(this code btw from this tutorial) when or how it should return true? I want to check if its true to enter another activity
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
when I am creating a user , I am adding Boolean true
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
editor.commit();
}
this method is to check the return islogin true or false in this case its always false, how to fix that to return it ?
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything\
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
else {
Intent i = new Intent(_context, UserProfile.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
Session manager class
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything\
* */
public void checkLogin(){
// Check login status
// editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
else {
Intent i = new Intent(_context, UserProfile.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
}
edit
when I removed the editor from the cursor and I add it here, it worked
public void checkLogin(){
// Check login status
pref = PreferenceManager.getDefaultSharedPreferences(_context);
editor = pref.edit();
editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
but the weird when If I am addin here , its not working
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
pref = PreferenceManager.getDefaultSharedPreferences(_context);
// pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
editor.putBoolean("login", true);
...
Instead of
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
try
pref = PreferenceManager.getDefaultSharedPreferences(context);
Here is my context (ctx) in the debugger.
So the following is how you can check the preference file to verify that it matches. I also wrote the code different in the third screen shot to demonstrate how a small difference can change the preference location.
In the first screen shot, notice the debugger showing the location of the preference file I am writing to.
Next, look at the location of the file I am reading from and how I initialized my pref variable. My saved preference is true, just as I saved it in the last screen.
Finally, I initialized my pref differently. See the difference? My boolean is now false(default) and the file location is different.
Now, maybe you are setting up your preferences the same every time. Check to be sure. I had this exact problem years ago and it drove me nuts till I realized I had different preference files being used. This is how I found the problem.
Finally, look at the different ways I tried to get my context. See how each one is different in the debugger? This is probably not your issue, but when you have weird disconnects going on, look twice at exactly how you hook everything up.
I hope this helps...
Make sure that the editor is connected to the SharedPreferences. I don't see something unusual but it would be safer to use prefs.edit()...commit();
You did not mention how you are retrieving the value. But while committing the value, are you writing to the same preference file that you are retrieving from ?
SharedPreferences myPref = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = myPrefFIle.edit();
editor.putBoolean("login", true);
editor.commit();
Otherwise, it is quite simple as you know.
EDIT
You can try this preference helper file. Replace your with this and try. If you still see the issue, then it is something else but not in preferences.
public class SharedPreferencesHelper {
public static final String PFO_SHARED_PREF_NAME = "prefs_file";
public static final String PREF_PLUG_STATE = "plug_state";
public static final String PREF_ICE_BUTTON_STATE = "ice_button_state";
private final SharedPreferences mPreferences;
private final Context mContext;
private static SharedPreferencesHelper instance = null;
private SharedPreferencesHelper(Context context) {
mContext = context;
mPreferences = context.getSharedPreferences(PFO_SHARED_PREF_NAME,
Context.MODE_PRIVATE);
}
public static SharedPreferencesHelper getInstance(final Context context) {
if (instance == null) {
instance = new SharedPreferencesHelper(context.getApplicationContext());
}
return instance;
}
public boolean getPlugState() {
return mPreferences.getBoolean(PREF_PLUG_STATE, false);
}
public void storePlugState(boolean state) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean(PREF_PLUG_STATE, state);
editor.apply();
}
}
You call like this, for ex:
boolean pullPlugState = mPref.getPlugState();
This is a singleton but you can change it once it starts working. Or else this is not a big object so it's perfectly fine with singleton.
This question already has answers here:
How to display a one time welcome screen?
(3 answers)
Closed 7 years ago.
I am creating a project where I have a login screen, which is used for user to login into the
Application. This login screen should only be visible the first time, so the user can fill it and log in, but when user opens the application at the second time the application must show main.activity. How to use Shared preferences to do this?
Save the login information of the user in SharedPeference:
SharedPreferences preferences = getSharedPreferences("preference",MODE_PRIVATE);
preferences.edit().putBoolean("LoggedIn", true).apply();
And save the boolean "LoggedIn" to false when the User logs out :
preferences.edit().putBoolean("LoggedIn", false).apply();
In the SplashActivity get the value from sharedprefence and call respective activities:
boolean loggedIn = preferences.getBoolean("LoggedIn", false);
if(loggedIn){
// call main activity
}else{
//call login activity
}
First, check whether user logged in before. Use SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Boolean loggedIn = prefs.getBoolean("loggedIn", false);
if(loggedIn != null && loggedIn)
{
//open main activity
}else{
//open login page
}
and when user logs in, save the login information to SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean("loggedIn", true);
That is all you need.
Try this, Working code
in your Login page
// Session Manager Class
SessionManagerFor_Signin session;
private EditText EMAIL, PASSWORD;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sign_in);
// Session Manager
session = new SessionManagerFor_Signin(getApplicationContext());
login = (Button) findViewById(R.id.loginbutton);
EMAIL = (EditText) findViewById(R.id.EmaileditText1);
PASSWORD = (EditText) findViewById(R.id.passwordeditText2);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = EMAIL.getText().toString();
password = PASSWORD.getText().toString();
if (email.equals("") || password.equals(""))
{
// user didn't entered user name or password
// Show alert asking him to enter the details
alert.showAlertDialog(sign_in.this, "Login Failed...","Please Enter Email and Password", false);
}
else
{
// fetch the Password form database for respective Email
storedPassword = DB.getSinlgeEntry(email);
if (password.equals(storedPassword))
{
session.createLoginSession(email, password);
Toast.makeText(sign_in.this, "Login Successfull",Toast.LENGTH_LONG).show();
Intent intent = new Intent(sign_in.this, Page1_Landing.class);
startActivity(intent);
finish();
}
}
break;
}
SessionManagerFor_Signin.java
public class SessionManagerFor_Signin
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "SharedPref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";
// Constructor
public SessionManagerFor_Signin(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
// Create login session
public void createLoginSession(String email, String password)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_EMAILID, email);
// Storing email in pref
editor.putString(KEY_PASSWORD, password);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin()
{
// Check login status
if(this.isLoggedIn())
{
Intent intent = new Intent(_context,Page1_Landing.class);
// Closing all the Activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Toast.makeText(getApplicationContext(),email, Toast.LENGTH_LONG).show();
_context.startActivity(intent);
}
else
{
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user mail
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
// user password
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent intent = new Intent(_context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
_context.startActivity(intent);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Further you want Reference Find below link
Link For Reference
SIf you want to do this with shared preferences when the user log in to the app share a preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", true).commit();
And if you want to log out on buton click set the preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", false).commit();
In order to start your app without log in screen you can use a splash screen before the others and check the shared preference...
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
Boolean state = prefs.getString("staylogin", false);
if (state) {
//Start Main Activity
} else {
//Start Log in activity
}
I have an app where a user logs in and his details are saved so that the next time he starts the app he doesn't need to log in again.I have used SharedPreferences for this purpose. Now when I implement a logout function, I clear the preferences and I get a Map with 0 elements. Also I delete the Preference file. But when another user logs in he can still see the previous users details instead of his. How can I solve this?
Here is my code:-
SessionManagement.java
public class SessionManagement extends Application
{
static SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// ContextS
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyUserDetails";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_USERSNAME = "usersname";
public static final String KEY_DEVICEREGISTERED = "deviceregistered";
// Constructor
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String emailId, String usersname)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putBoolean(KEY_DEVICEREGISTERED, true);
editor.putString(KEY_EMAILID, emailId);
editor.putString(KEY_USERSNAME, usersname);
editor.commit();
// commit changes
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails()
{
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, null));
// return user
return user;
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin()
{
// Check login status
if(!this.isLoggedIn())
{
// user is not logged in redirect him to Login Activity
Intent i =new Intent(this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
// This function clears all session data and redirect the user to LoginActivity
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.remove(KEY_EMAILID);
editor.remove(KEY_USERSNAME);
editor.remove(IS_LOGIN);
editor.clear();
editor.commit();
}
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Login.java
sessionManager = new SessionManagement(getApplicationContext());
if(sessionManager.isLoggedIn())
{
//Go directly to main activity
HashMap<String, String> userDetails = sessionManager.getUserDetails();
startMyActivity();
finish();
}
else
{
sessionManager.createLoginSession(email, username);
}
public void startMyActivity()
{
// TODO Auto-generated method stub
Intent in = new Intent(getApplicationContext(), Details1.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
}
Logout.java
SessionManagement session = new SessionManagement(getApplicationContext());
session.logoutUser();
ClearData cl = new ClearData();
cl.clearApplicationData(getApplicationContext());
Intent i = new Intent(Home.this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
ClearData.java
public class ClearData
{
public static void clearApplicationData(Context context)
{
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
File f = new File(appDir, s);
if(deleteDir(f))
Log.i("TAG", String.format("**************** DELETED -> (%s) *******************",
f.getAbsolutePath()));
}
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Instead of removing value from sharedpreference you can just edit value of sharedpreference with null value.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, null);
editor.putString(KEY_USERSNAME, null);
editor.commit();
}
i think this will work..
You can change the values of Shared preferences.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, "");
editor.putString(KEY_USERSNAME, "");
editor.clear();
editor.commit();
}
or You try this code. Clear your Shared preferences values.
pref.edit().clear().commit();
if your are using Marshmallow then
Add file in xml folder
mybackupscheme.xml
<full-backup-content>
<exclude domain="sharedpref" path="yourshared pref name.xml"/>
</full-backup-content>
then add in AndroidManifest.xml
<application
...
android:fullBackupOnly="false"
android:fullBackupContent="#xml/mybackupscheme"
/>
Hope this using this your issue will be resolved.
Try to get editor every time before calling commit().
If this not works, check contexts, that are returning preferences, they must be in one application and process.
I think problem is in your way of working with editor.
I think there is problem in your view of your editor and preference globalization you have to create preference and editor locally....
Because you are getting preferences
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
And now you are not getting any updated Preferences....
Each and every time when you have to work with your preferences...
Initialize preference and editor every time.
Either logging In or log out.