Question

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.

Was it helpful?

Solution

Make one class for your SharedPreferences

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();
    }

    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();

Do same for password

OTHER TIPS

You can achieve this by using AccountManager.

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 retrieve 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;
    }
}

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 use a boolean value in the SharedPreferences.

Load it before login to check if login is needed.

Save it after login.

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.

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;
    }
}

Source Code

https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc

Fetch Previous Login ID in android enter image description here

**After Login save Email ID is SharedPreferences** 

    emaidId = et_Email.getText().toString().trim();

    SharedPreferences ss = getSharedPreferences("loginSession_key", 0);
    Set<String> hs = ss.getStringSet("set", new HashSet<String>());
    hs.add(emaidId);
    SharedPreferences.Editor edit = ss.edit();
    edit.clear();
    edit.putStringSet("set", hs);
    edit.commit();

===================onCreate()====================
===================AutoCompleteTextView set Adapter===================

**Fetch PRevious Login Email id in email EditText**

SharedPreferences sss = getSharedPreferences("loginSession_key", 0);            // todo loginSession_key   key name ALWAYS SAME
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>()));
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String()));
ArrayList<String> al = new ArrayList<>();
al.addAll(sss.getStringSet("set", new HashSet<String>()));
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.select_dialog_item, al);
//Getting the instance of AutoCompleteTextView
et_Email.setThreshold(1);//will start working from first character
et_Email.setAdapter(adapter);//setting the adapter data into the 

Using this class will help you to store all types of sessions

public class Session {

    private SharedPreferences prefs;

    public Session(Context cntx) {
        // TODO Auto-generated constructor stub
        prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
    }

    public void set(String key,String value) {
        prefs.edit().putString(key, value).commit();
    }

    public String get(String key) {
        String value = prefs.getString(key,"");
        return value;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top