How to maintain session in android?

Can anybody tell me how to maintain session for a user login. For example when the user sign- in to an application they have to be signed in unless the user logouts or uninstall the application similar to gmail in android.

  • How can I use Tesseract in Android?
  • Restoring view hierarchy from saved state does not restore views added programatically
  • Generate a Random Color Java
  • How to align drawableLeft to top instead center in android TextView?
  • Android AlarmManager triggers every “round” 10 minutes
  • How to avoid a DialogFragment being dismissed when the Search button is pressed - Android
  • Gradle build error, Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'
  • Android Navigation Drawer bug using the sample
  • Unable to resolve imports from external dependencies in Android Studio 2.0 Preview 5 + Preview 6
  • Making the vertical scrollbar visible
  • Google/Apple Push Notification Service (APNS/GCM)
  • Unable to build apk: The number of method references cannot exceed 64K
  • 9 Solutions collect form web for “How to maintain session in android?”

    do like this make one class for your sharedpreference

    public class Session {
    
        private SharedPreferences prefs;
    
        public Session(Context cntx) {
            // TODO Auto-generated constructor stub
            prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
        }
    
        public void setusename(String usename) {
            prefs.edit().putString("usename", usename).commit();
            prefsCommit();
        }
    
        public String getusename() {
            String usename = prefs.getString("usename","");
            return usename;
        }
    }
    

    now after making this class when you want to use it, use like this: make object of this class like

    private Session session;//global variable 
    session = new Session(cntx); //in oncreate 
    //and now we set sharedpreference then use this like
    
    session.setusename("USERNAME");
    

    now whenever you want to get the username then same work is to be done for session object and call this

    session.getusename();
    

    best of luck 🙂 same for password

    You can use a boolean value in the SharedPreferences.

    Load it before login to check if login is needed.

    Save it after login.

    I have one simple way rather than maintain a session.

    i.e. Just store one boolean variable with your username and password. by default set value equal to false.

    After first successful login make its value to true.

    Then just check its value on your Mainactivity, if it is true then jump to next activity otherwise jump to login activity.

    You can achieve this by using Account Manager -click here
    code sample-
    //method to add account..
    private void addAccount(String username, String password) {

        AccountManager accnt_manager = AccountManager
                .get(getApplicationContext());
    
        Account[] accounts = accnt_manager
                .getAccountsByType(getString(R.string.account_type));//account name identifier.
    
        if (accounts.length > 0) {
            return;
        }
        final Account account = new Account(username,
                getString(R.string.account_type));
    
        accnt_manager.addAccountExplicitly(account, password, null);
    
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
        intent.putExtra(AccountManager.KEY_PASSWORD, password);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
                getString(R.string.account_type));
        // intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL,
        // PARAM_AUTHTOKEN_TYPE);
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token");
        this.setAccountAuthenticatorResult(intent.getExtras());
        this.setResult(RESULT_OK, intent);
        this.finish();
    
    }
    

    //method to retrive account.
    private boolean validateAccount() {

        AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
    
            @Override
            public void run(AccountManagerFuture<Bundle> arg0) {
                Log.e("calback", "msg");
    
                try {
                    Bundle b = arg0.getResult();
                    if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) {
                        //User account exists!!..
                    }    
    
                } catch (OperationCanceledException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (AuthenticatorException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
        };
    
        AccountManager accnt_manager = AccountManager
                .get(getApplicationContext());
    
        Account[] accounts = accnt_manager
                .getAccountsByType(getString(R.string.account_type));
    
        if (accounts.length <= 0) {
            return false;
        } else {
    
            loginNameVal = accounts[0].name;
            loginPswdVal = accnt_manager.getPassword(accounts[0]);
            return true;
    
        }
    
    }
    

    Use SharedPreferences.
    Code to save a value to sharedpreferences:

    SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
    SharedPreferences.Editor ed=sp.edit();
    ed.putInt("value", your_value);
    ed.commit();
    

    Code to get value from sharedpreferences:

    SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
    int value = sp.getInt("value", default_value);
    

    You can check login and logout by using this value.

    You can obtain that behaivour in a few different ways, the one I prefer is setting a flag in the shared prefs. whe a user logs in an check it when the app is started if you get the default value the user is not loggend, else you should have your flag (i use the user name) set and avoid the log-in section.

    save the user data in shared preferences till the user logs out.
    once user logs out clear the data from shared preferences.

    Use following code.

    SessionManager.java

    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 = "Pref";
    
        // 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
            editor.putBoolean(IS_LOGIN, true);
    
            // Storing name in pref
            editor.putString(KEY_NAME, name);
    
            // Storing email in pref
            editor.putString(KEY_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
            if(!this.isLoggedIn()){
                // user is not logged in redirect him 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);
            }
    
        }
    
    
    
        /**
         * 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, 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);
        }
    
        /**
         * Quick check for login
         * **/
        // Get Login State
        public boolean isLoggedIn(){
            return pref.getBoolean(IS_LOGIN, false);
        }
    }
    

    And in MainActivity do like the following.

    public class MainActivity extends Activity {
    
        // Email, password edittext
        EditText txtUsername, txtPassword;
    
        // login button
        Button btnLogin;
    
        // Alert Dialog Manager
        AlertDialogManager alert = new AlertDialogManager();
    
        // Session Manager Class
        SessionManager session;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login); 
    
            // Session Manager
            session = new SessionManager(getApplicationContext());                
    
            // Email, Password input text
            txtUsername = (EditText) findViewById(R.id.txtUsername);
            txtPassword = (EditText) findViewById(R.id.txtPassword); 
    
            Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
    
    
            // Login button
            btnLogin = (Button) findViewById(R.id.btnLogin);
    
    
            // Login button click event
            btnLogin.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
                    // Get username, password from EditText
                    String username = txtUsername.getText().toString();
                    String password = txtPassword.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("ABC", "abc@gmail.com");
    
                            // Staring MainActivity
                            Intent i = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(i);
                            finish();
    
                        }else{
                            // username / password doesn't match
                            alert.showAlertDialog(LoginActivity.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(LoginActivity.this, "Login failed..", "Please enter username and password", false);
                    }
    
                }
            });
        }        
    }
    
    public class Session {
    
        private SharedPreferences prefs;
    
        public Session(Context cntx) {
            // TODO Auto-generated constructor stub
            prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
            editor = prefs.edit();
        }
    
        public void setusename(String usename) {
            editor.putString("usename", usename).commit();
    
        }
    
        public String getusename() {
            String usename = prefs.getString("usename","");
            return usename;
        }
    }
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.