简体   繁体   English

共享首选项布尔值始终返回false

[英]shared preference Boolean is always returning false

I am using shared preference. 我正在使用共享首选项。 Why this method is always returning false ?(this code btw from this tutorial ) when or how it should return true? 为什么此方法总是返回false ?(在本教程中此代码)何时或如何返回true? I want to check if its true to enter another activity 我想检查输入其他活动是否正确

 public boolean isLoggedIn(){
        return pref.getBoolean("login", false);
    }

when I am creating a user , I am adding Boolean true 创建用户时,我要添加布尔值true

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

        // Storing name in pref
        editor.putString("name", name);

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

        // commit changes
        editor.commit();
    }

this method is to check the return islogin true or false in this case its always false, how to fix that to return it ? 此方法是检查return islogin是true还是false,在这种情况下,它始终是false,如何解决返回的问题?

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

Session manager class 会话管理器类

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
        Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
        System.out.println("login1");
        editor.putBoolean("login", true);

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

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

edit 编辑

when I removed the editor from the cursor and I add it here, it worked 当我从光标中删除editor并将其添加到此处时,它起作用了

public void checkLogin(){
    // Check login status
    pref = PreferenceManager.getDefaultSharedPreferences(_context);
    editor = pref.edit();

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

} }

but the weird when If I am addin here , its not working 但是奇怪的是,如果我在这里添加,它不起作用

public void createLoginSession(String name, String email){
    // Storing login value as TRUE
    Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
    System.out.println("login1");
    pref = PreferenceManager.getDefaultSharedPreferences(_context);
    // pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
    editor.putBoolean("login", true);
...

Instead of 代替

pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

try 尝试

pref = PreferenceManager.getDefaultSharedPreferences(context);

Here is my context (ctx) in the debugger. 这是调试器中的上下文(ctx)。

在此处输入图片说明

So the following is how you can check the preference file to verify that it matches. 因此,以下是如何检查首选项文件以确保其匹配的方法。 I also wrote the code different in the third screen shot to demonstrate how a small difference can change the preference location. 我还在第三幅屏幕截图中编写了不同的代码,以演示微小的差异如何改变首选项的位置。

In the first screen shot, notice the debugger showing the location of the preference file I am writing to. 在第一个屏幕截图中,请注意调试器显示了我正在写入的首选项文件的位置。 在此处输入图片说明

Next, look at the location of the file I am reading from and how I initialized my pref variable. 接下来,查看我正在读取的文件的位置以及如何初始化我的pref变量。 My saved preference is true, just as I saved it in the last screen. 我保存的首选项为true,就像我在上一个屏幕中保存的一样。 在此处输入图片说明

Finally, I initialized my pref differently. 最后,我以不同的方式初始化了我的偏好。 See the difference? 看到不同? My boolean is now false(default) and the file location is different. 我的布尔值现在为false(默认值),并且文件位置不同。 在此处输入图片说明

Now, maybe you are setting up your preferences the same every time. 现在,也许您每次都设置相同的首选项。 Check to be sure. 检查以确保。 I had this exact problem years ago and it drove me nuts till I realized I had different preference files being used. 几年前,我遇到了这个确切的问题,直到我意识到我使用了不同的首选项文件后,我才发疯。 This is how I found the problem. 这就是我发现问题的方式。

Finally, look at the different ways I tried to get my context. 最后,看看我尝试获取上下文的不同方式。 See how each one is different in the debugger? 看看调试器中的每一个有何不同? This is probably not your issue, but when you have weird disconnects going on, look twice at exactly how you hook everything up. 这可能不是您的问题,但是当您进行奇怪的断开连接时,请仔细查看如何正确连接所有内容。 在此处输入图片说明

I hope this helps... 我希望这有帮助...

Make sure that the editor is connected to the SharedPreferences. 确保编辑器已连接到SharedPreferences。 I don't see something unusual but it would be safer to use prefs.edit()...commit(); 我看不到异常,但是使用prefs.edit()... commit()会更安全。

You did not mention how you are retrieving the value. 您没有提到如何获取价值。 But while committing the value, are you writing to the same preference file that you are retrieving from ? 但是,在提交值时,是否正在写入要从中检索的同一首选项文件?

  SharedPreferences myPref = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = myPrefFIle.edit();
  editor.putBoolean("login", true);
  editor.commit();  

Otherwise, it is quite simple as you know. 否则,这很简单。

EDIT 编辑

You can try this preference helper file. 您可以尝试此首选项帮助文件。 Replace your with this and try. 替换为此,然后尝试。 If you still see the issue, then it is something else but not in preferences. 如果您仍然看到此问题,则可能是其他原因,但不是首选项。

public class SharedPreferencesHelper {

    public static final String PFO_SHARED_PREF_NAME = "prefs_file";

    public static final String PREF_PLUG_STATE = "plug_state";
    public static final String PREF_ICE_BUTTON_STATE = "ice_button_state";

    private final SharedPreferences mPreferences;
    private final Context mContext;
    private static SharedPreferencesHelper instance = null;


    private SharedPreferencesHelper(Context context) {
        mContext = context;
        mPreferences = context.getSharedPreferences(PFO_SHARED_PREF_NAME,
                Context.MODE_PRIVATE);
    }

    public static SharedPreferencesHelper getInstance(final Context context) {
        if (instance == null) {
            instance = new SharedPreferencesHelper(context.getApplicationContext());
        }

        return instance;
    }

    public boolean getPlugState() {
        return mPreferences.getBoolean(PREF_PLUG_STATE, false);
    }

    public void storePlugState(boolean state) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(PREF_PLUG_STATE, state);
        editor.apply();
    }
}  

You call like this, for ex: 您这样称呼,例如:

boolean pullPlugState = mPref.getPlugState();  

This is a singleton but you can change it once it starts working. 这是一个单例,但是一旦开始工作就可以更改。 Or else this is not a big object so it's perfectly fine with singleton. 否则,这不是一个大对象,因此对于单例来说完全可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM