How to clear db when app is uninstalled in android

2020-07-16 07:57发布

问题:

Im using database to store messages, and if i uninstall my app and again reinstall the same app, the db remains same, but i want to clear my database, how to solve this?

回答1:

To listen the uninstall event you have to implement a broadcast received, like:

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
    android:name=".UninstallIntentActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <action android:name="android.intent.action.DELETE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="package"  />
    </intent-filter>



</activity>

</application>

And then in your UninstallIntentActivity you have to use the next line to delete your database:

context.deleteDatabase(DATABASE_NAME);

You can see more about this topic here Listen Broadcast Before application uninstall

I hope this works for you.



回答2:

All data including databases,preference,local data files stored in internal storage are deleted on an uninstall.They will only stay intact on application update.



回答3:

I think it's not ordinary situation, cause when you uninstall app - all db are removed automaticaly. But if it doesn't happen - try to clear data in Menu - Manage App - your app - Clear data before uninstalling.



回答4:

In my case I just forgot to add below line in onUpgrade method of DatabaseHelper class

onCreate(sqLiteDatabase);


回答5:

below code can help you to delete your database from your application

/**
     * Re crate database
     * Delete all tables and create them again
     * */
    public void resetTables(){
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_NAME, null, null);
        db.close();
    }

make one method in class where you handle your database handling means. where you crate other methods like add,update etc..