首页 文章

SharedPreference - 清除和读取

提问于
浏览
0

我在SharedPreference中保存了一些数据 . 单击按钮时,用户将被注销,并通过调用pref.clear()ad pref.commit()清除sharedPreference . 当用户尝试重新登录时,编辑器将调用commit(),但不会保存新值 . 清除完成后,为什么共享偏好不能保存的任何建议?

清算部分:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
                               SharedPreferences.Editor sa = prefs.edit();
                               sa.clear();
                               sa.commit();

重新添加部分:

editor.putString("bucket", bucket);
            editor.putString("profileid", profileid);
            editor.putString("username", user);
            editor.putString("password", pass);
            editor.commit();

CLOSED :在底部回答,但对于正在寻找答案的其他人,我接受了答案

3 回答

  • 0

    其实我的错,在我启动我的偏好时有一个错字 . 对不起人!

  • 0

    让我向您展示一个如何在 SharedPeferences 中添加/读取/删除数据的工作示例 . 在 Activity 中将一些数据添加到 SharedPreferences

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("bucket", bucket);
    editor.putString("profileid", profileid);
    editor.putString("username", user);
    editor.putString("password", pass);
    editor.commit();
    

    当用户成功登录时,您可能希望执行上述操作 . 现在,当用户注销时,在 onClickListener 内注销 Button

    SharedPreferences settings = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.clear();
    editor.commit();
    

    因此,在您的 Activity 代码中,您应该检查是否已设置了 SharedPreferences 值 . 如果已设置,则可以将用户重定向到主屏幕,而无需再次登录 .

  • 0

    你是如何初始化编辑器的(我认为是SharedPreferences.Editor) . 我使用以下内容来获取编辑器 .

    SharedPreferences settings = getActivity().getSharedPreferences("a_string", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
    

    我这样做是为了清除和保存我的数据 .

    请求提供更多信息,如果这种剂量没有帮助 .

相关问题