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

This is my logout code using Intent, I want to clear the SharedPreference when I click logout button.

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();
Dumbo
  • 1,630
  • 18
  • 33
Manish Ahire
  • 550
  • 4
  • 19

4 Answers4

4

Use clear() method:

SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.clear()
editor.apply()
Dumbo
  • 1,630
  • 18
  • 33
will
  • 399
  • 1
  • 11
1

For API 24 (Nougat) or higher you can just call deleteSharedPreferences(String name)

context.deleteSharedPreferences("YOUR_PREFS");

However, there is no backward compatibility, so if you're supporting anything less than 24 you can use apply() for non-blocking asynchronous operation.

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

Or in your case,

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

commit() : writes the data synchronously (blocking the thread its called from) and returns about the success of the operation.

apply() : schedules the data to be written asynchronously. It does not inform you about the success of the operation.

As per official docuement, If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead of commit().

Priyank Patel
  • 12,244
  • 8
  • 65
  • 85
0
SharedPreferences preferences = context.getSharedPreferences("pref_name, Context.MODE_PRIVATE);
preferences.edit().clear().commit();
Yossi
  • 327
  • 2
  • 5
0
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.remove("UID");//your key
editor.commit();

clear() can remove all values from the preferences.

Jaydeep chatrola
  • 2,423
  • 11
  • 17