How to delete shared preferences data from App in Android

前端 未结 24 2463
日久生厌
日久生厌 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: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();
        }
    }
    

提交回复
热议问题