簡體   English   中英

如何在會話中存儲userid並在android中檢索另一個類?

[英]How To Store userid in session and retrieve it another class in android?

我想將userid保存在login.java類的會話中,並在另一個welcome.java類中進行檢索並將其吐司,而當我嘗試在welcome.java類中檢索userid時報錯,並且應用程序崩潰,並且如果我刪除檢索來自welcome.java類的userid代碼,然后可以正常工作而無需檢索userid。 所以請有人幫我在這里我想念的嗎?

這是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 = "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_userid = "userid";
        //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 userid, String email){
            // Storing login value as TRUE
            editor.putBoolean(IS_LOGIN, true);

            // Storing name in pref
            editor.putString(KEY_userid, userid);
            //editor.putString(KEY_NAME, name);

            // Storing email in pref
            editor.putString(KEY_EMAIL, email);

            // commit changes
            editor.commit();
        }   

        /**
         * Check login method will 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, Login.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_userid, pref.getString(KEY_userid, null));

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

            //Toast.makeText(SessionManager.this, "function call...: " , Toast.LENGTH_LONG).show();

            // After logout redirect user to Loing Activity
            Intent i = new Intent(_context, Login.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);

            //Intent intent = new Intent(getApplicationContext(), Second_activity.class);
            //startActivity(intent);

        }

        /**
         * Quick check for login
         * **/
        // Get Login State
        public boolean isLoggedIn(){
            return pref.getBoolean(IS_LOGIN, false);
        }



}

這是login.java代碼

   In this class i removed extra code just write relevant code where userid save in session after login success, 
   public class Login extends Activity {

private EditText editTextUserName;
private EditText editTextPassword;
SessionManager session;
String userid,;

String username;
String password,regid;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registeratin);


    session = new SessionManager(getApplicationContext());   

    editTextUserName = (EditText) findViewById(R.id.nameID);
    editTextPassword = (EditText) findViewById(R.id.et_pass_ID);


}

           respObject.getJSONObject("response");
                      userid = responses.getString("memberID");


                    String active = respObject.getString("status");
                    if(active.equalsIgnoreCase("200")){


                        session.createLoginSession(userid, "anroidhive@gmail.com");


                        Intent intent=new Intent(Login.this,Welcome.class);

                        startActivity(intent);
                        finish();

         }

 }

這是Welcome.java代碼

  Here i want to retrieve userid in this class that i saved before in login class, here i am writing only relevant code .
  public class Welcome extends Activity {

 SessionManager session;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    HashMap<String, String> user = session.getUserDetails();
    String userid = user.get(SessionManager.KEY_userid);


    Toast.makeText(this, userid+"", Toast.LENGTH_LONG).show();
  }
}

在這里,它在檢索用戶ID時出錯,並且應用程序崩潰了,如果我刪除了檢索到的代碼,則應用程序可以正常工作。 si認為我嘗試接收時存在錯誤,請有人幫助我,我該怎么辦? 我在這里想念什么?

會話未啟動,請檢查以下代碼,

public class Welcome extends Activity {

 SessionManager session;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    session = new SessionManager(getApplicationContext());//<-- this is what you missed
    HashMap<String, String> user = session.getUserDetails();
    String userid = user.get(SessionManager.KEY_userid);


    Toast.makeText(this, userid+"", Toast.LENGTH_LONG).show();
  }
}

建議為SessionManager使用單個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM