开发者

Problems using SQLiteOpenHelper, returns null on create, possible Thread issue

I have a ContentProvider named GeneralDataProvider. Which calls

@Override
public boolean onCreate() {
    mDatabaseOpenHelper = new DatabaseOpenHelper(getContext());
    return true;
}

Which looks like:

private static class DatabaseOpenHelper extends SQLiteOpenHelper {
    DatabaseOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e("DataBaseOpenHelper", "onCreate()");
        //The columns we'll include in the dictionary table
        //db.execSQL("CREATE TABLE general " + 
        // .. and more
    }
}

The problem

This works fine as long as I run managedQuery(...) inside an Activity, but when i try to execute the following code in a thread, I get a NullPointerException.

 public class SyncManager extends Thread {

         @Override
         public void run() {
            mIntent = new Intent();
            mIntent.setData(GeneralDataColumns.CONTENT_URI);
            GeneralDataProvider generalProvider = new GeneralDataProvider();
            mCursor = generalProvider.query(mIntent.getData(), GENERAL_PROJECTION, selection, null,
            GeneralDataColumns.DEFAULT_SORT_ORDER);
     }
 }

Which is executed from my main activity as such

    mSyncManager = new SyncManager();
    mSyncManager.start();

After digging deeper, it turns out that what causes the NullPointerException is the following line, inside GeneralDataProvider.query().

       SQLiteDatabase db = mDatabaseOpenHelper.getReadableDatabase();

Since mDatab开发者_高级运维aseOpenHelper is null.

Am I using my ContentProvider in an incorrect manner?

What I have tried: Added 'synchronized' to the query()-method inside my GeneralDataProvider


Turned out I was wrong.

The problem is that query() didn't work as I expected it to. I had to send a ContentResolver to my SyncManager-class as such

    mSyncManager = new SyncManager(getContentResolver());
    mSyncManager.start();

And then use that ContentResolver when performing the actual query.

    public SyncManager(ContentResolver context) {
        mContentResolver = context;
    }

    @Override
    public void run() {

       // General data
       mIntent = new Intent();
       mIntent.setData(GeneralDataColumns.CONTENT_URI);
       mCursor = mContentResolver.query(mIntent.getData(), GENERAL_PROJECTION, selection, null, GeneralDataColumns.DEFAULT_SORT_ORDER);
   }

This solved all of my problems!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜