Java SharedReferences未读取正确的上下文

Java SharedReferences未读取正确的上下文,java,android,Java,Android,我的代码中有一个问题,一个方法总是返回false,即使我插入true public boolean isLoggedIn(){ return pref.getBoolean("login", false); } 即使我在检查之前添加true,这段代码也会返回false * */ public void checkLogin(){ // Check login status editor.putBoolean("login

我的代码中有一个问题,一个方法总是返回false,即使我插入true

  public boolean isLoggedIn(){
        return pref.getBoolean("login", false);
    }
即使我在检查之前添加true,这段代码也会返回false

  * */
    public void checkLogin(){
        // Check login status

        editor.putBoolean("login", true);// even if add true it will return false

        if(!this.isLoggedIn()){
            Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
我试图做的是在操作栏中有一个
注册
按钮,一旦单击它,它将提供用户注册活动。然后,他将插入用户名和密码,并将其返回mainactivity。如果他再次点击
注册
按钮,它会将他发送到另一个活动,因为他的登录 在我的代码中,即使他登录,也会发送他注册活动,因为我上面解释的
假返回
是我的代码

会话管理器

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";
    //SharedPreferences.Editor editor;
    SharedPreferences.Editor editor;

    // Constructor
    public SessionManager(Context context){
        this._context = context;
       // pref = PreferenceManager.getDefaultSharedPreferences(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
        Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
        System.out.println("login1");
        editor.putBoolean("login", true);
        System.out.println(pref.getBoolean("login", false));
        // Storing name in pref
        editor.putString("name", name);

        // Storing email in pref
        editor.putString("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
      //  editor.putBoolean("login", true);
        editor.putBoolean("login", true);

        if(!this.isLoggedIn()){
            Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, Register.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);
        }
else {
            Intent i = new Intent(_context, UserProfile.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, MainActivity.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("login", false);
    }
}
登记册

SessionManager session;
    Button btnLogin;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

       final AlertDialogManager alert = new AlertDialogManager();

        session=  GlobalContext.getInstance().getSession();

        usernam = (EditText) findViewById(R.id.username);
        passw = (EditText) findViewById(R.id.password);
        email = (EditText) findViewById(R.id.email);
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
        btnLogin = (Button) findViewById(R.id.login);
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get username, password from EditText
                String username = usernam.getText().toString();
                String password = passw.getText().toString();

                // Check if username, password is filled
                if(username.trim().length() > 0 && password.trim().length() > 0){
                    // For testing puspose username, password is checked with sample data
                    // username = test
                    // password = test
                    if(username.equals("test") && password.equals("test")){

                        // Creating user login session
                        // For testing i am stroing name, email as follow
                        // Use user real data
                        session.createLoginSession("test", "test");

                        // Staring MainActivity
                        Intent i = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(i);
                        finish();

                    }else{
                        // username / password doesn't match
                        alert.showAlertDialog(Register.this, "Login failed..", "Username/Password is incorrect", false);
                    }
                }else{
                    // user didn't entered username or password
                    // Show alert asking him to enter the details
                    alert.showAlertDialog(Register.this, "Login failed..", "Please enter username and password", false);
                }

            }
        });

    }

您需要执行提交,以便在首选项中保存值 所以,在添加任何writeeditor.commit()之后,请检查更新的方法

public void checkLogin(){
    // Check login status

    editor.putBoolean("login", true);// even if add true it will return false
    editor.commit();

    if(!this.isLoggedIn()){
        Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();

它会的,请再试一次。使用编辑器在首选项中添加所有值后。如果
public SessionManager(Context-Context){this.\u Context=Context;//pref=PreferenceManager.getDefaultSharedReferences(Context);pref=\u Context.getSharedReferences(pref_NAME,PRIVATE_模式);editor=pref.edit();}
被调用或未被调用,则执行editor.commitTry解压缩。我只看到
session=GlobalContext.getInstance().getSession()并且不知道它是否构造了sessionmanager变量?我知道您从中获得了示例,您将在sessionmanager中找到它,如下所示
session=newsessionmanager(getApplicationContext())
@BNK是的,这是上下文的问题,我通过为会话创建一个类来解决它
public void checkLogin(){
    // Check login status

    editor.putBoolean("login", true);// even if add true it will return false
    editor.commit();

    if(!this.isLoggedIn()){
        Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();