How to delete shared preferences data from App in Android

前端 未结 24 2170
日久生厌
日久生厌 2020-11-22 14:37

How do I delete SharedPreferences data for my application?

I\'m creating an application that uses a lot of web services to sync data. For testing purposes, I need to

相关标签:
24条回答
  • 2020-11-22 15:18
    new File(context.getFilesDir(), fileName).delete();
    

    I can delete file in shared preferences with it

    0 讨论(0)
  • 2020-11-22 15:19

    My solution:

    SharedPreferences preferences = getSharedPreferences("Mypref", 0);
    preferences.edit().remove("text").commit();
    
    0 讨论(0)
  • 2020-11-22 15:19

    None of the answers work for me since I have many shared preferences keys.

    Let's say you are running an Android Test instead of a unit test.

    It is working for me loop and delete through all the shared_prefs files.

    @BeforeClass will run before all the tests and ActivityTestRule

    @BeforeClass
    public static void setUp() {
        Context context = InstrumentationRegistry.getTargetContext();
    
        File root = context.getFilesDir().getParentFile();
        String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
        for (String fileName : sharedPreferencesFileNames) {
            context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:23

    Seems that all solution is not completely working or out-dead

    to clear all SharedPreferences in an Activity

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

    Call this from the Main Activity after onCreate

    note* i used .apply() instead of .commit(), you are free to choose commit();

    0 讨论(0)
  • 2020-11-22 15:24

    To remove the key-value pairs from preference, you can easily do the following

    getActivity().getSharedPreference().edit().remove("key").apply();
    

    I have also developed a library for easy manipulation of shared preferences. You may find the following link

    https://github.com/farruhha/SimplePrefs

    0 讨论(0)
  • 2020-11-22 15:25

    As of API 24 (Nougat) you can just do:

    context.deleteSharedPreferences("YOUR_PREFS");
    

    However, there is no backward compatibility, so if you're supporting anything less than 24, stick with:

    context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply(); 
    
    0 讨论(0)
提交回复
热议问题