How to maintain session in android?
Asked Answered
R

12

26

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.

Rebarebah answered 19/12, 2013 at 10:8 Comment(1)
Have you tried using SharedPreferences as a session storage facility? Not really sure about safety/security issues but it may be what you need.Alla
C
47

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

Cloudburst answered 19/12, 2013 at 10:14 Comment(6)
what is the purpose of prefsCommit();Pet
Consider using apply() instead; commit() writes its data to persistent storage immediately whereas apply() will handle it in the background.Pet
i am getting red line on prefsCommit();Levite
There is no need of again prefCommit.Pleae ignore that line of code(LOC).Elaineelam
Why I have this error?-> error: cannot find symbol variable PreferenceManager when I implement this class.Justus
Storing a password in the SharedPreferences seems like a bad idea, why not use a unique sessionID?Space
L
16

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;
    }
}
Lely answered 19/12, 2013 at 10:21 Comment(1)
This is the correct way of handling sessions. Thank you!Halfon
B
2

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.

Brenna answered 19/12, 2013 at 10:15 Comment(2)
do you think its safe?Indignant
Yes of course, because shared preferences is always stored in data. so no one can import data from "DEVICES". Still u don't satisfied then u can store username and password in encrypted form. @IndignantBrenna
E
1

You can use a boolean value in the SharedPreferences.

Load it before login to check if login is needed.

Save it after login.

Elison answered 19/12, 2013 at 10:12 Comment(0)
P
1

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.

Parshall answered 19/12, 2013 at 12:29 Comment(0)
I
0

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.

Iscariot answered 19/12, 2013 at 10:12 Comment(0)
C
0

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

Copolymer answered 19/12, 2013 at 10:15 Comment(2)
will the user able to maintain the session even after they close the application without logout?Rebarebah
yes. he will be able to. you are going to clear the sharedprefs only if he presses the logout button. until unless the sharedprefs will be saved internally to your application.Copolymer
E
0
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;
    }
}
Elaineelam answered 25/5, 2017 at 18:46 Comment(0)
C
0

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 
City answered 19/9, 2017 at 12:19 Comment(0)
H
0

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;
    }
}
Hid answered 31/8, 2018 at 4:25 Comment(0)
E
0

Through this format, you can set or get multiple objects of data, you don't need to create separate functions to store different models in SharedPreferences.

* Here in this format, you don't need to pass your object KEY for putString() and getString()
* Using the object class name you are able to identify your session object uniquely, for both setModel() and getModel()
public class Session {

private final SharedPreferences pref;

public Session(Context ctx) {
    pref = PreferenceManager.getDefaultSharedPreferences(ctx);
    //pref = ctx.getSharedPreferences("IDENTIFIED_NAME", Context.MODE_PRIVATE);
}

public <U> void setModel(U obj) {
    pref.edit().putString(getClassName(obj), SerializeObject(obj)).apply();
}

/* Parameter Example: Class.class */
public <U> U getModel(Class<U> type) {
    String user = pref.getString(type.getSimpleName(), null);
    if (isEmptyOrNull(user)) {
        return null;
    }
    return DeserializeObject(user, type);
}





/* The below functions are for support, You can move the below part to your own BaseUtil class. */
public static boolean isEmptyOrNull(String data) {
    if (data == null) {
        return true;
    }

    if (data.isEmpty() || data.trim().isEmpty()) {
        return true;
    }

    return false;
}

public static String getClassName(Object obj) {
    return obj.getClass().getSimpleName();
}

public static String SerializeObject(Object myObject) {
    // serialize the object
    try {
        Gson gson = new Gson();
        String json = gson.toJson(myObject);
        return json;
    } catch (Exception e) {
        System.out.println(e);
        return null;
    }
}

public static <U> U DeserializeObject(String serializedObject, Class<U> type) {
    // serialize the object
    try {
        if (serializedObject == null || serializedObject.isEmpty()) {
            return null;
        }
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        U data = gson.fromJson(serializedObject, type);
        return data;
    } catch (Exception e) {
        System.out.println(e);
        return null;
    }
}
}

Create an object class (file_name: UserModel.java)

public class UserModel {
    public String userId;
    public String firstName;
    public String lastName;
    public String email;
    public String phone;
}

How to use - For setModel() and getModel()

//creating an instance of the Session class
Session session = new Session(ctx); // Here you have to pass the Context(ctx)

// setting value in the UserModel
UserModel obj = new UserModel();
obj.firstName = "Apu";
obj.lastName = "Pradhan";
obj.email = "[email protected]";
obj.phone = "123456789";

// set UserModel in the Session
session.setModel(obj);

//getting UserModel data from the Session
UserModel userData = session.getModel(UserModel.class);
Expenditure answered 22/12, 2022 at 13:26 Comment(0)
H
0

Simplest way to create event listener on Firestore then use this code

    public static void newsession(Activity context) {
            long unixTime = System.currentTimeMillis() / 1000L; // Convert milliseconds to seconds
            String Oldsession = String.valueOf(unixTime);
            db.collection("USER").document(UserAccount).update("Session", String.valueOf(Oldsession));
            DocumentReference userDocRef = db.collection("USER").document(UserAccount);
    
            userDocRef.addSnapshotListener(new EventListener() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot snapshot,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
    
                        return;
                    }
    
                    if (snapshot != null && snapshot.exists()) {
                        // Get the current Session value from the document
                        String sessionValue = snapshot.getString("Session");
                        if (!Oldsession.equals(sessionValue)) {
                            Appsettings.ShowToast(context, "ERROR SESSION EXPIERD");
                            Intent i = new Intent(context, Activity_Login.class);
    
                            // on below line we are
                            // starting a new activity.
                            context.startActivity(i);
                            context.finish();
                        }
    
                    } else {
                    }
                }
            });
        }

 
Hobie answered 15/5 at 8:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.