简体   繁体   中英

MyContentProvider.onCreate() is not being called?

The onCreate of my userDatabase that extends ContentProvider is not properly called

Here is some of my userBatabase code:

public class userDatabase extends ContentProvider {

    private MainDatabaseHelper mOpenHelper;

    public userDatabase(){}

    public static final class MainDatabaseHelper extends SQLiteOpenHelper{...}

    @Override
    public boolean onCreate() {
        mOpenHelper = new MainDatabaseHelper(getContext());     
        return true;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long id = mOpenHelper.getWritableDatabase().insert("Users", null, values);
        return Uri.withAppendedPath(CONTENT_URI, "" + id);
    }

    ...
}

In my main activity I call:

userDatabase cpDatabase = new userDatabase();

But when I try to call cpDatabase.insert(userDatabase.CONTENT_URI, values);

Everything crashes inside insert when mOpenHelper.getWritableDatabase().insert("Users", null, values); is called.

I found out that mOpenHelper.getWritableDatabase() was the issue, as it wont run even by itself, and then I found out this was because mOpenHelper was null.

I instantiate mOpenHelper in the constructor, so I figure its not running. A few log messages confirm this, when I call userDatabase cpDatabase = new userDatabase(); my log messages showed that the userDatabase() constructor ran normally, but the onCreate never ran, so the mOpenHelper never got instantiated.

(Note: with these log messages, I noticed that the constructor and the onCreate for my userDatabase got called when my app started. I have no idea why or where. I dont understand why this was run before i tried to create an instance. and even though it was run, mOpenHelper still wasn't initialized, and when i created an instance, the constructor ran but the onCreate didnt.)

What could possibly be happening, and how can I make my onCreate run?

Since you are using content providers, according to the documentation

This method is called for all registered content providers on the application main thread at application launch time

And the way you try to use the content provider is seems wrong and, You don't need to manually instantiate the content provider, once you made the request via the ContentResolver by passing the URI, the system inspects the authority of the given URI and passes the request to the content provider registered with the authority.

for example

getContentResolver().delete(uri, null, null);

Where the uri is, the full URI to query.

This tutorial will guide you in right direction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM