Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep android applications always be logged in state?

Right now I am trying to create one Android application, assume it is going to be some "X" concept okay. So I am creating one login screen. What I want to do is at once if I logged in that application on my mobile, it should always be logged in whenever I try to access that application.

For example our Facebook, g-mail and yahoo etc.. in our mobile phones

What to do for that?

like image 353
Rohith Avatar asked Oct 05 '12 10:10

Rohith


People also ask

How do I keep my Android app logged in?

When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out. Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.

How do I stay logged in to Webview?

two ways either save your user login username and password to sharedprefrence and check it everytime or save your user login username and password to sqlite and check if cursor count is 1 then redirect to webview else type username and password.

What is the most appropriate way to store user settings in Android application?

User settings are generally saved locally in Android using SharedPreferences with a key-value pair. You use the String key to save or look up the associated value.


1 Answers

Use Shared Preference for auto login functionality. When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out.

Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.

To achieve this first create a class, in this class you need to write all the function regarding the get and set value in the sharedpreference. Please look at this below Code.

public class SaveSharedPreference  {     static final String PREF_USER_NAME= "username";      static SharedPreferences getSharedPreferences(Context ctx) {         return PreferenceManager.getDefaultSharedPreferences(ctx);     }      public static void setUserName(Context ctx, String userName)      {         Editor editor = getSharedPreferences(ctx).edit();         editor.putString(PREF_USER_NAME, userName);         editor.commit();     }      public static String getUserName(Context ctx)     {         return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");     } } 

Now in the main activity (The "Activity" where users will be redirected when logged in) first check

if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0) {      // call Login Activity } else {      // Stay at the current activity. } 

In Login activity if user login successful then set UserName using setUserName() function.

like image 129
Chirag Avatar answered Sep 30 '22 22:09

Chirag