Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 共享首选项布尔值始终返回false_Java_Android - Fatal编程技术网

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

Java 共享首选项布尔值始终返回false,java,android,Java,Android,我使用共享偏好。为什么此方法总是返回false?(此代码在此顺带一提)何时或如何返回true?我想检查进入另一个活动是否为真 public boolean isLoggedIn(){ return pref.getBoolean("login", false); } 当我创建一个用户时,我添加布尔值true public void createLoginSession(String name, String email){ // Storing lo

我使用共享偏好。为什么此方法总是返回
false
?(此代码在此顺带一提)何时或如何返回true?我想检查进入另一个活动是否为真

 public boolean isLoggedIn(){
        return pref.getBoolean("login", false);
    }
当我创建一个用户时,我添加布尔值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();
    }
这个方法是检查返回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);
        }
    }
会话管理器类

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

但奇怪的是,如果我在这里,它不工作

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

确保编辑器已连接到SharedReferences。我没有看到异常情况,但使用prefs.edit()…commit()会更安全

确保编辑器已连接到SharedReferences。我没有看到异常情况,但使用prefs.edit()…commit()会更安全

您没有提到如何检索值。但是,在提交值时,您是否正在写入要从中检索的同一首选项文件

  SharedPreferences myPref = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = myPrefFIle.edit();
  editor.putBoolean("login", true);
  editor.commit();  
否则,正如你所知,这是非常简单的

编辑

您可以尝试此首选项帮助文件。用这个替换您的,然后再试一次。如果您仍然看到这个问题,那么它是其他问题,但不在首选项中

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();
    }
}  
你这样叫,比如:

boolean pullPlugState = mPref.getPlugState();  

这是一个单例,但一旦它开始工作,您可以更改它。或者这不是一个大的对象,所以它与singleton完美结合

您没有提到如何检索值。但是,在提交值时,您是否正在写入要从中检索的同一首选项文件

  SharedPreferences myPref = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = myPrefFIle.edit();
  editor.putBoolean("login", true);
  editor.commit();  
否则,正如你所知,这是非常简单的

编辑

您可以尝试此首选项帮助文件。用这个替换您的,然后再试一次。如果您仍然看到这个问题,那么它是其他问题,但不在首选项中

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();
    }
}  
你这样叫,比如:

boolean pullPlugState = mPref.getPlugState();  
这是一个单例,但一旦它开始工作,您可以更改它。或者这不是一个大的对象,所以它与singleton完美结合

而不是

pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
试一试

这是调试器中的我的上下文(ctx)

因此,下面是如何检查首选项文件以验证它是否匹配。我还在第三个屏幕截图中编写了不同的代码,以演示一个小的差异如何改变首选项位置

在第一个屏幕截图中,请注意调试器显示了我要写入的首选项文件的位置。

接下来,查看我正在读取的文件的位置,以及我是如何初始化pref变量的。我保存的首选项为true,就像我在上一个屏幕中保存的一样。

最后,我以不同的方式初始化了pref。看到区别了吗?“我的布尔值”现在为false(默认值),并且文件位置不同。

现在,也许您每次都在设置相同的首选项。检查确认一下。几年前我就遇到了这个问题,这让我发疯,直到我意识到我使用了不同的偏好文件。这就是我发现问题的原因

最后,看看我试图获得上下文的不同方式。在调试器中查看每个调试器的不同之处?这可能不是你的问题,但是当你有奇怪的断开连接时,仔细看看你是如何连接所有东西的。

我希望这有助于…

而不是

pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
试一试

这是调试器中的我的上下文(ctx)

因此,下面是如何检查首选项文件以验证它是否匹配。我还在第三个屏幕截图中编写了不同的代码,以演示一个小的差异如何改变首选项位置

在第一个屏幕截图中,请注意调试器显示了我要写入的首选项文件的位置。

接下来,查看我正在读取的文件的位置,以及我是如何初始化pref变量的。我保存的首选项为true,就像我在上一个屏幕中保存的一样。

最后,我以不同的方式初始化了pref。看到区别了吗?“我的布尔值”现在为false(默认值),并且文件位置不同。

现在,也许您每次都在设置相同的首选项。检查确认一下。几年前我就遇到了这个问题,这让我发疯,直到我意识到我使用了不同的偏好文件。这就是我发现问题的原因

最后,看看我试图获得上下文的不同方式。在调试器中查看每个调试器的不同之处?这可能不是你的问题,但是当你有奇怪的断开连接时,仔细看看你是如何连接所有东西的。


我希望这有助于…

当你保存时,你有editor.putBoolean(“login”,true);当您阅读它时,您有pref.getBoolean(“login”,false);。我的第一个想法是如何初始化pref和editor。您可能正在从不同的位置保存和阅读。我是SharedReference的新手,我使用一个类作为共享首选项,并且仅访问它。我会发布课程的完整代码
sessionmanagement
@Tequilaman请看下面我的答案。我在一个应用程序上有一些冲突,现在我很小心如何获得我的SharedReference。如果在使用pref或editor的位置放置断点,则可以在调试模式下查看源代码;当您阅读它时,您有pref.getBoolean(“login”,false);。我的第一个想法是如何初始化pref和editor。您可能正在从不同的位置保存和阅读。我是SharedReference的新手,我使用一个类作为共享首选项,并且仅访问它。我会发布课程的完整代码
sessionmanagement
@Tequilaman请看下面我的答案。我在一个应用程序上有一些冲突,现在我很小心如何获得我的SharedReference。如果在使用pref或editor的位置放置断点,则可以在调试模式下查看源代码。如何确保其已连接?请解释如何使用prefs.edit()我还添加了完整的类sessionmanager?如何确保其