5

I'm having hard time trying to figure out how to use SharedPreferences to store the username in the phone and stay in session until logout. I also need to know how at the same time its in session it will send the username out with the data the user click on within the listview. Below are the codes I am using and would like to know where and what code to put in order to acheive this. As login it will go to the menu and stay at the menu (avoid the backbutton from going back to the login screen) Every menu have a logout item which will go back to the login screen.

The previous questions i've looked at are this and this

Logcat Detail

05-26 10:42:19.146: WARN/KeyCharacterMap(26071): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-26 10:42:23.926: DEBUG/AndroidRuntime(26071): Shutting down VM
05-26 10:42:23.926: WARN/dalvikvm(26071): threadid=3: thread exiting with uncaught exception (group=0x40013140)
05-26 10:42:23.926: ERROR/AndroidRuntime(26071): Uncaught handler: thread main exiting due to uncaught exception
05-26 10:42:23.936: ERROR/AndroidRuntime(26071): java.lang.NullPointerException
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.merrill2.Login$1.onClick(Login.java:42)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.View.performClick(View.java:2232)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.View.onTouchEvent(View.java:3905)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.widget.TextView.onTouchEvent(TextView.java:6414)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.View.dispatchTouchEvent(View.java:3421)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:906)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:906)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:906)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:906)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1707)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1197)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.app.Activity.dispatchTouchEvent(Activity.java:1993)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1691)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1533)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.os.Looper.loop(Looper.java:123)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at android.app.ActivityThread.main(ActivityThread.java:3992)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at java.lang.reflect.Method.invokeNative(Native Method)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at java.lang.reflect.Method.invoke(Method.java:521)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
05-26 10:42:23.936: ERROR/AndroidRuntime(26071):     at dalvik.system.NativeStart.main(Native Method)
05-26 10:42:23.946: INFO/Process(899): Sending signal. PID: 26071 SIG: 3
05-26 10:42:23.956: INFO/dalvikvm(26071): threadid=7: reacting to signal 3
05-26 10:42:23.966: INFO/dalvikvm(26071): Wrote stack trace to '/data/anr/traces.txt'
05-26 10:42:25.646: DEBUG/dalvikvm(25722): GC freed 973 objects / 63040 bytes in 93ms
05-26 10:42:27.777: DEBUG/DispatchService(945): Handled message = TIMED_SERVICE_UNMASK
05-26 10:42:29.856: DEBUG/DispatchService(945): DISPATCH SERVICE getIdenPacketDataState: returning: 4
05-26 10:42:29.876: INFO/iDENWAPReceiver(953): Received a android.intent.action.ANY_DATA_STATE

Login.java

public class Login extends Activity {
    protected static final SharedPreferences settings = null;
    private EditText etUsername;
    private Button btnLogin;
    private Button btnCancel;
    private TextView lblResult;
    /** Called when the activity is first created. */
    //@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        etUsername = (EditText)findViewById(R.id.username);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);

        btnLogin.setOnClickListener(new OnClickListener() {
            //@Override
            public void onClick(View v) {
            // Check Login
            String username = etUsername.getText().toString();

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("username", username);

            if(username.equals("1111")){
                lblResult.setText("Login successful.");

                //startActivity(new Intent(this, Activity2.class));


                Intent i = new Intent(getApplicationContext(), Customer.class);
                startActivity(i);

if i take out the line below:

protected static final SharedPreferences settings = null;

i put this:

btnLogin.setOnClickListener(new OnClickListener() {
            private SharedPreferences settings;

'settings' is giving error so i had to use one of those line mentioned above

Community
  • 1
  • 1
merrill
  • 593
  • 5
  • 14
  • 34

4 Answers4

18

To add the user just do:

import android.preference.PreferenceManager;
....
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);

And to delete it, in Logout:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.remove("username");

This way you make sure that the user only lasts for one session, until it logs out. You should make a check (just in case), when you open your app, to see if there is an username already set from a previous session if something wrong happened.

And as for passing the data in a ListView, you have to do it by hand. SharedPreference framework takes care of everything else.

ferostar
  • 7,074
  • 7
  • 38
  • 61
  • Can I get a sample to grab that user name to send out with the data? Where exactly where I put the SharedPreferences within the code? – merrill May 24 '11 at 16:08
  • I updated the code above. first I get getDefaultSharePreferences error the fix option is getPreferences() and other is fix option is create method 'getDefaultSharePreferences(context). The other error is the username (the second username without the quote) to create a field of username or change to etUsername but if I change to etUsername the new error is putString and had to create private String etUsername but it would conflict with the EditText etUsername. How to I go from there? – merrill May 25 '11 at 15:00
  • By the way, once log in can a user go 'back' to login screen? I would like to avoid the login screen (once login) the whole session until logout. – merrill May 25 '11 at 15:03
  • Just updated my answer, in order for it to work you need to import PreferenceManager, which has the method getDefault... That would be the correct way to do it. You made another two questions here... as for the username, pass the data as etUsername.getText().toString(), checking first that is not null. And as for the user to be unable to come back to the login screen the are a couple of ways to do it, try first making the activity no_history="true" in the Manifest (you can also finish() the activity after loading the next screen). – ferostar May 25 '11 at 15:16
  • Sorry I should be more clear on my last comment. Those errors are after I imported. With the updated answers you added the work settings is a new error (fix option is create field(or etc) for 'settings' or change to 'Settings'(android.provider))...can you give me more details on the username I still cant pick that up of what you said. – merrill May 25 '11 at 15:32
  • Please try again, i tried it and it works. As of the username, there is no username variable, that was an example only. If you want to save the username entered by the user in the etUsername field, you have to pass as parameter that very same text with etUsername.getText().toString(). Try reading some online documentation. – ferostar May 25 '11 at 15:38
  • I put the SharedPref in the login with no error and was able to compile it but when i press login button it force close. Am I missing something here? – merrill May 26 '11 at 16:18
  • You asked how to work with SharedPreferences. Now you are having another problem, not related at all... or yes, no one knows if you doesn't even show the logcat. There might be zillions of reasons that may be the cause of that error, related to this thing or not. Check the logcat, if it's something that has to do with SharedPreferences update it here, if not try to solve it or, if you can't find a solution for yourself, make another question. – ferostar May 26 '11 at 16:27
  • This is related to sharedPref. I have a logcat updated in my post now. Without the sharedpref I have no problem but when I put the sharedPref it force close when i click on login button. – merrill May 26 '11 at 17:47
  • I really don't know what you are doing, you have to clean your question and your code. You have in your question two versions of the code, erase the old one. As of the NullPointerException, you are doing SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = settings.edit();. If you can see, you are refering to a "settings" variable that doesn't exists, is created the line above but with the name of prefs. Please read your code before asking. – ferostar May 26 '11 at 18:07
  • I just edit my post and deleted the old code with the updated code =)...As if now, I am trying to get the sharedpref to work. I could not figure out how to fix the 'settings' error without using variable. – merrill May 26 '11 at 20:25
  • Just replace this line: SharedPreferences.Editor editor = settings.edit(); whit this line: SharedPreferences.Editor editor = prefs.edit(); – ferostar May 26 '11 at 22:45
  • Also consider calling `editor.commit()` or `editor.apply()` to store the changes in persistent storage. – Jonik Oct 27 '13 at 08:54
8

I think this example should be very helpful.

http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

The main class is here:

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
        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);
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Sam003
  • 331
  • 3
  • 3
  • 1
    This is a really indeed very nice example... very very... its very structured, re-usable and easy to understand – Paul Okeke Apr 29 '15 at 03:48
5

When the user logs in successfully, add the user's username to the SharedPreference for your application.

SharedPreferences settings = getSharedPreferences("MyPrefsFile", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);

Every time the user opens the app, check to see if the "userID" preference is set. If it is then he is logged in. otherwise show the Login screen. When the user logs out, delete the "username" entry from the shared prefs.

I also need to know how at the same time its in session it will send the username out with the data the user click on within the listview

You will have access to the user's ID through that shared pref so you are able to use it whenever you need it. The Android framework does not do that for you but it's a simple task for you to do.

Haphazard
  • 10,900
  • 6
  • 43
  • 55
  • Can I get a sample to grab that user name to send out with the data? Where exactly where I put the SharedPreferences within the code? – merrill May 24 '11 at 16:08
  • `SharedPreferences settings = getSharedPreferences("MyPrefsFile", 0); String username = settings.getString("username", null);` I can't tell you how to communicate that info to your server as I do not know anything about the protocols and architecture that you are using. You put that code wherever you need access to the username. – Haphazard May 24 '11 at 16:17
  • I have the code for http and have succeeded to send data to the server. Im trying to figure out how to grab that username info to go with the data. As for sharedpref, can it keep the user away from login screen during the whole session unless logout? – merrill May 24 '11 at 16:37
  • You can use it to see if anyone is logged in: if `settings.getString("username", null);` returns `null` then the user is not logged in. If you are using URI/URLs to pass data, just throw something like `"site.com/path?user="+username` – Haphazard May 24 '11 at 16:42
  • I updated the code above. first I get getDefaultSharePreferences error the fix option is getPreferences() and other is fix option is create method 'getDefaultSharePreferences(context). The other error is the username (the second username without the quote) to create a field of username or change to etUsername but if I change to etUsername the new error is putString and had to create private String etUsername but it would conflict with the EditText etUsername. How to I go from there? – merrill May 25 '11 at 15:00
  • You deleted your own line `String username = etUsername.getText().toString();` in the updated field. Of course it doesn't work if you don't define the `username` variable. – Haphazard May 25 '11 at 15:08
  • I never deleted the line String username. Its a copy-paste of that specific section didn't want to copy the whole code =). it is still giving that same error with everything else in there except for the sharedpref code and imported pref – merrill May 25 '11 at 15:27
  • Federico suggests doing it this way - perhaps it will work better: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = settings.edit(); editor.putString("username", username); – Haphazard May 25 '11 at 15:33
-1

for storing in stored preferences use this

 SharedPreferences.Editor editor = getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                        editor.putString("DeviceToken","ABABABABABABABB12345");
editor.apply();

for retrieving the same use

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
    String deviceToken = prefs.getString("DeviceToken", null);
Syed Danish Haider
  • 1,334
  • 11
  • 15