spacecowboy / NotePad

Now under new management
GNU General Public License v3.0
382 stars 158 forks source link

Removing data from the database #363

Closed Domuska closed 8 years ago

Domuska commented 8 years ago

Hello!

I'm not quite certain how I should be in contact with you so I decided to do it in here.

I am in the process of making some GUI related tests for the project and was wondering if there is a convenience method available for removing all the added data from the database and possibly other data the app happens to make when an user is using it, shared preferences and whatnot it might have.

If there are not, could you consider implementing them or pointing me to the direction on how to implement those myself, they would make the job of building the GUI tests much easier since I could just remove the added data in a teardown method instead of having to remove the app data through ADB commands.

spacecowboy commented 8 years ago

Cool! That sounds great.

Unfortunately, there isn't such a method. There are tests which do similar things though. For example, have a look at: https://github.com/spacecowboy/NotePad/blob/master/app/src/androidTest/java/com/nononsenseapps/notepad/test/DBFreshTest.java

So this might just do the trick:

@Before
public void clearData() {
    // Remove preferences
    PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit();
    // Physically delete the database file
    context.deleteDatabase(DatabaseHandler.DATABASE_NAME);
    // This should recreate the DB
    DatabaseHandler.getInstance(context).getReadableDatabase();
}
Domuska commented 8 years ago

Thanks for the response. That worked quite nicely.

However if running the tests in sequence the app is not restarted between the tests and the DatabaseHandler goes stale - this requires a method for refreshing it after the database is deleted.

Since it's maybe not preferable to have a random method that creates a new instance in a singleton class I guess it might be best to add a method for the DatabaseHandler to do the deleting - it can then refresh itself when it knows the database file has been removed:

public static void resetDatabase(Context context){
    context.deleteDatabase(DatabaseHandler.DATABASE_NAME);
    singleton = new DatabaseHandler(context);
    DatabaseHandler.getInstance(context).getWritableDatabase();
}
spacecowboy commented 8 years ago

@Domuska Yes that is a good idea. I've added some methods. See 8b6d082adb164ec637fcc19cf1b021fa5f66d83c

It will show some example usage as well. Hope that helps you.