【问题标题】:How to clear SharedPreferences during Logout? [duplicate]如何在注销期间清除 SharedPreferences? [复制]
【发布时间】:2018-09-22 07:47:25
【问题描述】:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Login.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UID", jobj1.getString("admin_id").toString());
editor.apply();

Toast toast = Toast.makeText(Login.this, "Login Successfully", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent i1=new Intent(Login.this,DashBoard.class);
startActivity(i1);
finish();

这是我使用 Intent 的注销代码,我想在单击注销按钮时清除 SharedPreference

case "Logout":
              Intent i5=new Intent(context1, Login.class);
              i5.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              context1.startActivity(i5);
              ((DashBoard)context1).finish();
              Toast.makeText(context1,"Logout",Toast.LENGTH_LONG).show();

【问题讨论】:

  • 问之前有没有试过搜索?
  • 是的,先生,但代码对我不起作用。
  • 代码应该做什么?哪个代码不起作用?究竟有什么不同?
  • code not work for me 显示您尝试了哪些代码。
  • logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 启动新闻源屏幕 SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE); SharedPreferences .Editor editor = preferences.edit(); editor.clear(); editor.commit(); finish(); });

标签: java android sharedpreferences logout android-sharedpreferences


【解决方案1】:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.remove("UID");//your key
editor.commit();

clear() 可以从首选项中删除所有值。

【讨论】:

    【解决方案2】:

    对于 API 24 (Nougat) 或更高版本,您只需致电 deleteSharedPreferences(String name)

    context.deleteSharedPreferences("YOUR_PREFS");
    

    但是,没有向后兼容性,因此如果您支持小于 24 的任何内容,则可以使用 apply() 进行非阻塞异步操作。

    context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply(); //apply() for non-blocking asynchronous operation 
    

    或者在你的情况下,

    PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
    

    commit() : 同步写入数据(阻塞调用它的线程)并返回操作成功。

    apply() : 安排异步写入数据。它不会通知您操作是否成功。

    As per official docuement, 如果您不关心返回值并且您在应用程序的主线程中使用它,请考虑使用apply() 而不是commit()

    【讨论】:

      【解决方案3】:

      使用clear()方法:

      SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
      editor.clear()
      editor.apply()
      

      【讨论】:

        【解决方案4】:
        SharedPreferences preferences = context.getSharedPreferences("pref_name, Context.MODE_PRIVATE);
        preferences.edit().clear().commit();
        

        【讨论】:

        • 会更喜欢 .apply() 而不是 .commit() ,因为 *apply 是异步调用
        猜你喜欢
        • 2014-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 2020-09-05
        相关资源
        最近更新 更多