Wouter
Wouter

Reputation: 2653

ContentProvider: managedQuery() works; query() fails

Within my app I'm in the process of wrapping the database access into a ContentProvider. This because occasionally I have crashes because two threads access the database at the same time. I rely heavily on background threads to pull down data from a web server and put that in the database; when the user switches between activities you may have multiple of those running at the same time. That's the why.

Now the how. I've implemented the ContentProvider class, and that seems to work fine. Registered in the manifest, and this also shows up in LogCat that the provider is active.

The app, with all its activities, accesses the database through a wrapper class which itself is not an activity. The constructor of this class takes the context of the calling activity as parameter. Nothing special there.

Now my problem: When accessing the content provider through the context.query() method, I get a crash:

04-15 23:05:33.699: ERROR/AndroidRuntime(3564): Caused by: java.lang.NullPointerException
04-15 23:05:33.699: ERROR/AndroidRuntime(3564):     at android.content.ContentResolver.acquireProvider(ContentResolver.java:727)
04-15 23:05:33.699: ERROR/AndroidRuntime(3564):     at android.content.ContentResolver.query(ContentResolver.java:239)
04-15 23:05:33.699: ERROR/AndroidRuntime(3564):     at squirrel.DeaddropDroid.DeaddropDB.query(DeaddropDB.java:482)

The offending line is:

final Cursor blog2 = db.query(DeaddropDB.BLOG_TABLE, new String[] {
            DeaddropDB.KEY_ID, DeaddropDB.KEY_DATE,
            DeaddropDB.KEY_BLOG_SUMMARY }, null, null,
            DeaddropDB.KEY_DATE + " DESC");

db is a DB object, the constructor takes the activity's context as parameter. In the same activity, the following line works as expected and gives the correct results:

final Cursor blog = managedQuery(DeaddropDBProvider.BLOG_URI,
            new String[] {DeaddropDB.KEY_ID, DeaddropDB.KEY_DATE,
            DeaddropDB.KEY_BLOG_SUMMARY }, null, null,
            DeaddropDB.KEY_DATE + " DESC");

This proves that my ContentProvider works and is registered properly. I'm really at a loss on what's going on here! Why does this query not work as advertised?

Upvotes: 0

Views: 2526

Answers (1)

Wouter
Wouter

Reputation: 2653

And finally, as promised, my answer.

Right, so it was my fault after all (of course). Took some digging in Android's sources (another thumbs-up for open sources), and with some further testing I found the reason. My Uri was null! I try to import the uri from the provider but there something goes wrong. That's going to be my next question, as while I have the workaround, I don't understand why it goes wrong.

That's my next question: Load URI from myContentProvider fails (null result), as while I have a working solution, I don't understand why it goes wrong. Further details on the issue are over there.

Upvotes: 2

Related Questions