删除数据库后,ContentProvider未调用onCreate

时间:2017-02-15 12:47:56

标签: android android-contentprovider android-database android-application-class

我创建了ContentProvider,可以在应用程序启动时创建一个数据库

现在在该应用程序中,当用户从应用程序注销时,我正在执行删除数据库的过程。

之后,当我再次登录时,ContentProvider无法调用覆盖类的 onCreate()

有没有办法使用ContentProvider重新创建数据库?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,

首先,我提到Refresh/Reload database reference in custom ContentProvider after restore但对答案不满意,因为它只是用于关闭数据库。

所以我创建了如下答案:

<强> DBHelper.java

/**
 * Delete database
 */
public static void reCreateDatabase(Context mContext) {
    ContentResolver resolver = mContext.getContentResolver();
    ContentProviderClient client = resolver.acquireContentProviderClient(KOOPSContentProvider.AUTHORITY);

    assert client != null;
    KOOPSContentProvider provider = (KOOPSContentProvider) client.getLocalContentProvider();

    assert provider != null;
    provider.resetDatabase();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        client.close();
    else
        client.release();

    LOGD("Database Deleted...");
}

public void removeDatabase(Context mContext) {
    mContext.deleteDatabase(DATABASE_NAME);
    LOGD("Database Deleted...");
}

<强> KOOPSContentProvider.java

public void resetDatabase() {
    if(dbHelper != null) {
        dbHelper.removeDatabase(getContext());
        dbHelper = new DbHelper(getContext());
    } else {
        LOGD("Database NULL");
    }
}

使用为:

DbHelper.reCreateDatabase(mContext);

谢谢:) :))