我正在尝试实现一个围绕SQLite数据库的ContentProvider。
我在构建ContentProvider时遵循了教程: tutorial
我想测试我拥有的东西;所以我试图实例化我的新ContentProvider,从查询处理程序中检索一个Cursor,并将它附加到我的CursorAdapter。目前,我在onCreate of my Activity中这样做(我知道这是不好的做法,我只是在测试,我最终会将它转移到服务中)。
Uri uri = Uri.parse("content://com.test.db.providers.Messages/messages");
String s[] = {"_id", "delivery_id", "user_id", "created_on", "subject", "summary", "messagetext", "read", "status"};
MessagesProvider p = new MessagesProvider();
if (p.open()) {
Cursor messages = p.query(uri, s, null, null, null);
startManagingCursor(messages);
}
当我启动应用程序时,我的扩展ContentProvider的onCreate方法会被执行。创建数据库帮助程序对象,创建数据库,并且onCreate方法返回true。但是,当我尝试使用我的ContentProvider(使用上面的代码)时,在open()方法中创建数据库帮助程序对象,但getWritableDatabase()返回null。另外,当我调用open()时,对getContext()的引用为null。
注意:其他一切似乎都运转正常。当我调用查询时,它会命中我的查询处理程序,识别Uri并尝试运行我的查询代码(由于数据库对象为空,这显然会爆炸)。
以下是我的扩展ContentProvider和数据库助手:
package com.test.db.providers;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import com.test.db.DbDefinitions;
import com.test.db.DbHelper;
public class MessagesProvider extends ContentProvider {
private DbHelper mDbHelper;
private SQLiteDatabase mDb;
private static final UriMatcher sUriMatcher;
private static final String PROVIDER_NAME = "com.test.db.providers.Messages";
private static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/messages");
public static final String id = "_id";
public static final String delivery_id = "delivery_id";
public static final String user_id = "user_id";
public static final String created_on = "created_on";
public static final String subject = "subject";
public static final String summary = "summary";
public static final String messagetext = "messagetext";
public static final String status = "status";
private static final int MESSAGES = 1;
private static final int MESSAGES_ID = 2;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(PROVIDER_NAME, "messages", MESSAGES);
sUriMatcher.addURI(PROVIDER_NAME, "messages/#", MESSAGES_ID);
}
public boolean open() {
mDbHelper = new DbHelper(getContext());
mDb = mDbHelper.getWritableDatabase();
return (mDb == null) ? false : true;
}
public void close() {
mDbHelper.close();
}
@Override
public boolean onCreate () {
mDbHelper = new DbHelper(getContext());
mDb = mDbHelper.getWritableDatabase();
return (mDb == null) ? false : true;
}
@Override
public String getType (Uri uri) {
switch (sUriMatcher.match(uri)) {
case MESSAGES:
return "vnd.android.cursor.dir/com.test.messages";
case MESSAGES_ID:
return "vnd.android.cursor.item/com.test.messages";
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch (sUriMatcher.match(uri)) {
case MESSAGES:
return queryMessages(uri, projection, selection, selectionArgs, sortOrder);
default:
throw new IllegalArgumentException("Unknown Uri " + uri);
}
}
@Override
public Uri insert (Uri uri, ContentValues initialValues) {
switch (sUriMatcher.match(uri)) {
case MESSAGES:
return insertMessages(uri, initialValues);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public int update (Uri uri, ContentValues values, String selection, String[] selectionArgs) {
switch (sUriMatcher.match(uri)) {
case MESSAGES:
return updateMessages(uri, values, selection, selectionArgs);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public int delete (Uri uri, String selection, String[] selectionArgs) {
switch (sUriMatcher.match(uri)) {
case MESSAGES:
return deleteMessages(uri, selection, selectionArgs);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
/*
* Messages
*/
private Cursor queryMessages(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor c = mDb.query(DbDefinitions.TABLE_MESSAGES, projection, selection, selectionArgs, null, null, sortOrder);
if (c != null) {
c.moveToFirst();
}
return c;
}
private Uri insertMessages(Uri uri, ContentValues initialValues) {
ContentValues values;
if (initialValues != null)
values = new ContentValues(initialValues);
else
values = new ContentValues();
long rowId = mDb.insert(DbDefinitions.TABLE_MESSAGES, summary, values);
if (rowId > 0) {
Uri messageUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(messageUri, null);
return messageUri;
}
throw new SQLException("Failed to insert new message " + uri);
}
private int updateMessages(Uri uri, ContentValues values, String where, String[] whereArgs) {
int result = mDb.update(DbDefinitions.TABLE_MESSAGES, values, where, whereArgs);
getContext().getContentResolver().notifyChange(uri, null);
return result;
}
public int deleteMessages(Uri uri, String where, String[] whereArgs) {
// TODO flag message as deleted
return 0;
}
}
package com.test.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DbDefinitions.DATABASE_NAME, null, DbDefinitions.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DbDefinitions.DB_CREATE);
db.execSQL(DbDefinitions.DB_TEST_DATA);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO run upgrade string
db.execSQL("DROP TABLE IF EXISTS " + DbDefinitions.TABLE_MESSAGES);
onCreate(db);
}
}
我想知道我是否应该以某种方式引用在启动应用程序时创建的MessagesProvider的任何实例,而不是声明一个新的(p)并使用它?
我将Activity中的onCreate代码更新为以下内容,但managedQuery返回null:
Uri uri = Uri.parse("content://com.test.db.providers.Messages/messages");
String s[] = {"_id", "delivery_id", "user_id", "created_on", "subject", "summary", "messagetext", "read", "status"};
Cursor messages = managedQuery(uri, s, null, null, null);
if (messages != null)
startManagingCursor(messages);
ExampleCursorAdapter msg =
new ExampleCursorAdapter(this, messages);
setListAdapter(msg);
答案 0 :(得分:3)
在撰写其他内容之前:先看看Android Developer网站上的Notepad example。在我看来,它是了解ContentProviders如何实现的一个很好的例子。
在研究了这个例子之后,我会坚持他们在那里编写ContentProviders的方式,以及他们如何从UI调用它来检索数据。
例如,您不需要“open()”方法。你可以在你的活动上做什么只是
@Override
public void onCreate(Bundle savedInstanceState){
...
if (getIntent().getData() == null) {
getIntent().setData(MyMetaData.CONTENT_URI);
}
Cursor cursor = managedQuery(getIntent().getData(), null, null, null, null);
//create an appropriate adapter and bind it to the UI
...
}
这将自动调用能够处理给定内容uri的ContentProvider,前提是您在manifest.xml文件中注册了它,如
<provider android:name=".provider.MyContentProvider" android:authorities="com.mycompany.contentprovider.MyContentProvider" />
//正如旁注 由于我更喜欢自动化单元测试并且你提到你只想测试你的ContentProvider是否真的有用,你也可以考虑针对它编写单元测试,更具体地说是ProviderTestCase2:
public class MessagesProviderTest extends ProviderTestCase2<MessagesProvider> {
private MockContentResolver mockResolver;
public MessagesProviderTest() {
super(MessagesProvider.class, MessagesMetaData.AUTHORITY);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mockResolver = getMockContentResolver();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
mockResolver = null;
//clean the old db
getContext().getDatabasePath("test.messages.db").delete();
}
public void testRetrieveMessages() {
//TODO insert some using ContentValues
//try to retrieve them
Cursor readMessagesCursor = mockResolver.query(....);
assertTrue("The cursor should contain some entries", readMessagesCursor.moveToFirst());
...
}
}
这只是一个旁注,但我确实推荐这个,因为这样你可以
答案 1 :(得分:0)
你仍然这样做吗?通常,provider-tag必须放在application-tag中。是的,我已将以下内容放在标记之前的标记内:“&lt;”提供者android:name =“com.test.db.providers.MessagesProvider”android:authorities =“com.test.db.providers .MessagesProvider “/&gt;” 中