我定义了一个内容提供商,并使我的数据库助手成为一个全局变量,我在onCreate方法中初始化。但是,在query((方法中,该全局变量的值为null。
这是我的内容提供商:
/** Tag for the log messages */
public static final String LOG_TAG = FeedingProvider.class.getSimpleName();
// Declaring a FeedingDbHelper variable;
private FeedingDbHelper mDbHelper;
/** URI matcher code for the content URI for the pets table */
private static final int FEEDINGS = 100;
/** URI matcher code for the content URI for a single pet in the pets table */
private static final int FEEDING_ID = 101;
/**
* UriMatcher object to match a content URI to a corresponding code.
* The input passed into the constructor represents the code to return for the root URI.
*/
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// Static initializer. This is run the first time anything is called from this class.
static {
// The calls to addURI() go here, for all of the content URI patterns that the provider
// should recognize. All paths added to the UriMatcher have a corresponding code to return
// when a match is found.
sUriMatcher.addURI(FeedingContract.CONTENT_AUTHORITY, FeedingContract.PATH_FEEDINGS,
FEEDINGS);
sUriMatcher.addURI(FeedingContract.CONTENT_AUTHORITY, FeedingContract.PATH_FEEDINGS +
"/#", FEEDING_ID);
}
/**
* Initialize the provider and the database helper object.
*/
@Override
public boolean onCreate() {
mDbHelper = new FeedingDbHelper(this.getContext());
// Make sure the variable is a global variable, so it can be referenced from other
// ContentProvider methods.
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Log.d(LOG_TAG, "Test in query: " + (mDbHelper == null));
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match) {
case FEEDINGS:
cursor = db.query(FeedingContract.FeedingEntry.TABLE_NAME, projection, selection,
selectionArgs, null, null, sortOrder);
break;
case FEEDING_ID:
selection = FeedingEntry._ID + "=?";
selectionArgs = new String[] {
String.valueOf(ContentUris.parseId(uri))
};
cursor = db.query(FeedingContract.FeedingEntry.TABLE_NAME, projection, selection,
selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Can't find uri in PetProvider.query()");
}
Log.e("Gerke", "Cursor: " + DatabaseUtils.dumpCursorToString(cursor));
return cursor;
}
结果错误消息是:
"java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.example.android.smartfeed.data.FeedingDbHelper.getReadableDatabase()'
上的null对象参考"
我的问题是:为什么全局变量mdbhelper null而不是我的dbhelper的实例?还尝试将上下文保存到全局变量,但这也不起作用。
我发现自己的错误:ContentProvider的定义很好,但是当使用它时,我尝试创建一个新实例,这是错误的。
所以对于其他所有有问题的人来说:与ContentProvider的通信是通过ContentResolver完成的。要获取ContentResolver的实例,请致电GetContentResolver((;