The document states that we should return true if the provider was successfully loaded, false otherwise. In my implementation, I would return false if DatabaseHelper == null.
Suppose now DatabaseHelper == null
and false is returned in onCreate, and query the provider somewhere in the code later, the provider is still being queried and of coz it would crash.
My question is what is the use to return false in OnCreate of ContentProvider? And how should I handle for the query after a fail onCreate? just run again the onCreate in query?
what is the use to return false in OnCreate of ContentProvider?
By quickly navigating through the Android source I found that, as for now, it really does not matter what you return, it just get ignored, again as for now.
On tests and ActivityThread
, attachInfo
is called right after newInstance
so if you look at ContentProvider
source at line 1058 is where onCreate
is called and looks like:
/**
* After being instantiated, this is called to tell the content provider
* about itself.
*
* @param context The context this provider is running in
* @param info Registered information about this content provider
*/
public void attachInfo(Context context, ProviderInfo info) {
/*
* We may be using AsyncTask from binder threads. Make it init here
* so its static handler is on the main thread.
*/
AsyncTask.init();
/*
* Only allow it to be set once, so after the content service gives
* this to us clients can't change it.
*/
if (mContext == null) {
mContext = context;
mMyUid = Process.myUid();
if (info != null) {
setReadPermission(info.readPermission);
setWritePermission(info.writePermission);
setPathPermissions(info.pathPermissions);
mExported = info.exported;
}
ContentProvider.this.onCreate();
}
}
Keep in mind that if documentation says so who knows, maybe this will be used/fixed in future releases.
how should I handle for the query after a fail onCreate? just run again the onCreate in query?
I would say yes, not necessarily onCreate
but your very own method that initializes once and ensures your DatabaseHelper
or so, that would be your best effort, I mean according to documentation of onCreate
You should defer nontrivial initialization (such as opening, upgrading, and scanning databases) until the content provider is used
So technically you would be doing as intended, yet it is wild out there so be safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With