Android:保持用户名在会话中直到注销

时间:2011-05-24 14:44:01

标签: android session android-activity sharedpreferences

我很难弄清楚如何使用SharedPreferences将用户名存储在手机中并保持会话直到退出。我还需要知道它在会话中的同时它将使用用户在列表视图中单击的数据发送用户名。下面是我正在使用的代码,并想知道在哪里以及为了实现这一目的而放置什么代码。登录后,它将进入菜单并停留在菜单上(避免后退按钮返回登录屏幕)每个菜单都有一个退出项目,将返回登录屏幕。

我之前看过的问题是thisthis

Logcat详细信息

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

如果我拿出以下一行:

protected static final SharedPreferences settings = null;

我说这个:

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

'settings'给出了错误,所以我不得不使用上面提到的那一行

4 个答案:

答案 0 :(得分:17)

要添加用户,请执行以下操作:

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

要删除它,请退出:

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

这样,您可以确保用户只持续一个会话,直到它注销。您应该在打开应用程序时进行检查(以防万一),看看是否有错误发生在上一次会话中的用户名。

至于在ListView中传递数据,你必须手动完成。 SharedPreference框架负责其他所有事情。

答案 1 :(得分:8)

我认为这个例子应该非常有用。

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

主要课程在这里:

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

答案 2 :(得分:5)

当用户成功登录后,将用户的username添加到您应用的SharedPreference

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

每次用户打开应用程序时,请检查是否设置了“userID”首选项。如果是,则他登录。否则显示登录屏幕。当用户注销时,从共享首选项中删除“用户名”条目。

  

我还需要知道如何在会话中同时发送用户名,用户点击列表视图中的数据

您可以通过共享的pref访问用户的ID,这样您就可以在需要时使用它。 Android框架并没有为您做到这一点,但这是一项简单的任务。

答案 3 :(得分:0)

用于存储在存储的首选项中使用此

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

用于检索相同的用途

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
    String deviceToken = prefs.getString("DeviceToken", null);