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.
Related
I have two activities namely Registration and Login where I defined a Shared Preferences in the Registration class. On the Registration page, if you click on the button that takes you to the Login Activity from the Registration Activity. I am storing a Shared Preferences value, so that on launching the app the second time, let the app immediately go to the LoginActivity instead of opening the first Activity which is Registration Activity. Here is my SharedPreferences class called Session.
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename).commit();
editor.commit();
public Boolean contKey(String key){
if (prefs.contains(key)){
return true;
}else{
return false;
}
}
Here is the button in the RegstrationActivity that stores the SharedPreferences value before going to the LoginActivity so that on launch the second time, it opens the LoginActivity class
loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session = new Session(getApplicationContext());
session.setusename("hello123");
Intent intent = new Intent(getApplication(),ActivityLogin.class);
startActivity(intent);
finish();
}
});
I have defined this in the onCreate method of RegistrationActivity class to switch to the ActivityLogin screen on next time the app is launched
System.out.println("it got here...2");
try {
if (session.contKey("username")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Please why is my Shared Preferences not switching to the LoginActivity the second time the is launched. Kindly assist
TRy this
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename);
editor.commit();
}
}
public String getusename() {
return prefs.getString("username","");
}
}
than use this way to get value SharedPreferences
session = new Session(getApplicationContext());
session.setusename("hello123");
String username=session.getusename();
Sample code
try {
if (!session.getusename().equals("")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Instead of default shared preference, you can define a private one with your desired name in the Activity A..like as follows..
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
SharedPreferences.Editor editor= preferences.edit();
editor.putString("userName","raju");
editor.commit();
If you want to retrieve that value from shared preferences in Activty A(I mean in the same activity), you can use following code..
String user_name= preferences.getString("userName","N/A");
or else in Activity B(I mean in some other activty), this time you don't need editor(for retrieval)..the code will be as follows
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
String user_name= preferences.getString("userName","N/A");
So I'm new to android and I have developed a simple alarm clock app. Problem is that my alarms resets when I reboot my phone, so I created a receiver which starts at boot. This receiver is supposed to get my list of quickAlarms from my shared preference, loop through it and then send them to my AlarmService. The problem is that I am unable to get hold of the sharedPreference.
I have tried these methods:
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
This is the broadcastReceiver called upon boot:
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BootReceiver", "BootReceiver called");
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
//sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
if(sharedPref.contains("alarm")){
Log.d("BootReceiver", "SharedPreference do contain alarms, trying to set them...");
alarmService= new AlarmService(context);
activate(context);
}else{
Log.d("BootReceiver", "SharedPreference does not contain any alarms.");
//I always get this message, so sharedPref never contains anything here!
}
}
/**
* Loops through the stored list of QuickAlarms, checks if the are set to on and then reshedules them.
* #param context
*/
public void activate(Context context) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
Iterator<QuickAlarm> alarmIterator = alarmList.iterator();
while(alarmIterator.hasNext()){
if(alarmIterator.next().isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", alarmIterator.next().getTime()).setAction("CREATE").putExtra("repeat", alarmIterator.next().getRepeat()).putExtra("id" , alarmIterator.next().getID()).putExtra("desc", alarmIterator.next().getDesc()));
}
}
Log.d("BootReceiver", "All alarms are set again!");
}}
Here is the code in MainActivity were I declare the sharedpreference and use it in the Controller class:
private SharedPreferences sharedPref;
//...
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
controller = new Controller(sharedPref, this.getApplicationContext());
Then it's really the Controller which use it:
public Controller(SharedPreferences sharedPref, Context context) {
this.context = context;
this.sharedPref = sharedPref;
editor = sharedPref.edit();
}
//...
public void addQuickAlarm(QuickAlarm qa, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarms;
if (gson.fromJson(sharedPref.getString("alarm", ""), type) == null) {
alarms = new ArrayList<>();
} else {
alarms = gson.fromJson(sharedPref.getString("alarm", ""), type);
}
if (id == -10) {
alarms.add(qa);
Log.d("Controller", "QuickAlarm added to pref");
} else {
alarms.remove(id);
alarms.add(id, qa);
Log.d("Controller", "QuickAlarm edited to pref");
}
String jsonAlarm = gson.toJson(alarms); //converting list to json and saving back
editor.putString("alarm", jsonAlarm);
editor.commit();
}
public void activateAlarm(boolean on, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
QuickAlarm qa = alarmList.get(id);
qa.setActive(on);
int[] repeat = qa.getRepeat();
addQuickAlarm(qa, id);
if (on) {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CREATE").putExtra("repeat", repeat).putExtra("id" , id).putExtra("desc", qa.getDesc()));
} else {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CANCEL").putExtra("id" , id));
}
}
you need to add the "alarm" key and its value to your sharedpreference when you are setting the alarm alert something like this
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
or
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor=sharedPref.edit();
editor.putString("alarm", "value u want to keep");
editor.commit();
Unable to start receiver com.example.user.alarmclock.Local.StartMyServiceAtBootReceiver: java.util.NoSuchElementException because after alarmIterator.next().isActive() this you are calling another next() like this alarmIterator.next().getTime() which mean you are asking for List<QuickAlarm > next item object(QuickAlarm ) which is not there so only you are getting the error. change your code to this because even you mean if in this object(QuickAlarm ) isActive() is true then pull other info from this object(QuickAlarm ) like getTime(),getRepeat() etc.
while(alarmIterator.hasNext()){
QuickAlarm qm=alarmIterator.next()
if(qm.isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qm.getTime()).setAction("CREATE").putExtra("repeat", qm.getRepeat()).putExtra("id" , qm.getID()).putExtra("desc", qm.getDesc()));
}
}
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
}
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.