【问题标题】:How to clear shared preferences from fragment?如何从片段中清除共享偏好?
【发布时间】:2017-01-16 10:19:43
【问题描述】:

如何从片段中清除共享首选项?谢谢

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);

        editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
        Intent logout = new Intent(getActivity(), LoginActivity.class);
        startActivity(logout);
        Log.d(TAG, sharedPreferences.getString("username", ""));
        Log.d(TAG, sharedPreferences.getString("password", ""));
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_logout, container, false);
    }

我的片段

【问题讨论】:

  • 你想达到什么目的?
  • 我想从活动中获取共享偏好,然后从片段中清除,这可能吗?
  • 当前代码有什么问题?
  • 这应该可以,但如果你愿意,你可以使用 editor.remove("key-value*").commit();
  • 我想,我无法清除共享偏好。

标签: android android-fragments sharedpreferences


【解决方案1】:

您可以直接使用偏好名称并从任何地方清除它。

SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("shared_pref_key").commit();

SharedPreferences preferences = context.getSharedPreferences("Mypref", Context.MODE_PRIVATE);
preferences .edit().clear().commit();

【讨论】:

    【解决方案2】:

    使用这样的东西:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_logout, container, false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);
    
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
        Intent logout = new Intent(getActivity(), LoginActivity.class);
        startActivity(logout);
        Log.d(TAG, sharedPreferences.getString("username", ""));
        Log.d(TAG, sharedPreferences.getString("password", ""));
        // Inflate the layout for this fragment
        return view;
    }
    

    【讨论】:

    • 还是不行,谢谢解答。我认为我的程序有问题,因为 log.d 没有显示。
    • @DennyKurniawan 如果您的 log.d 未显示,则表示您的键值对已从 sharedprefrence 中删除。
    • @Denny 如果你看不到你的日志意味着你的偏好值被清除了,很简单。
    • @W4R10CK 感谢您的帮助
    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多