如何确定内容提供商是否包含数据?

时间:2011-06-03 22:46:28

标签: android android-contentprovider

基本上,我有这个内容提供程序,我用它来存储和检索数据库中的一些数据。在我的一个活动中,我有一个向这个数据库添加数据的功能;但是,我不希望有重复的条目。我的功能看起来像这样:

public void addData(String data) {
  if ( /* data is not already in database */ ) {
    ConstantValues values = new ConstantValues();
    values.put(DATA_FIELD, data);
    getContentResolver().insert(CONTENT_URI, values);
  } else {
    // do nothing, it's already there
  }
}

现在,我的问题是,如何检查数据是否已由内容提供商存储?

修改

这是我的内容提供商的代码:

DataProvider.java

package org.frxstrem.xend;
import java.util.HashMap;
import org.frxstrem.xend.Data.Commands;
import org.frxstrem.xend.Data.SerialNumbers;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
public class DataProvider extends ContentProvider {

    private static final String DB_NAME = "xsend";
    private static final int DB_VERSION = 1;

    private static final String TABLE_SN = "serial_numbers";
    private static final String TABLE_CMD = "commands";

    private static final int SN = 1;
    private static final int SN_ID = 2;
    private static final int CMD = 3;
    private static final int CMD_ID = 4;

    private static HashMap<String, String> snpm;
    private static HashMap<String, String> cmdpm;
    private static final UriMatcher uriMatcher;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context c) {
            super(c, DB_NAME, null, DB_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + TABLE_SN + " ("
                    + SerialNumbers._ID + " INTEGER PRIMARY KEY, "
                    + SerialNumbers.TEXT + " TEXT"
                    + ");");
            db.execSQL("CREATE TABLE " + TABLE_CMD + " ("
                    + Commands._ID + " INTEGER PRIMARY KEY, "
                    + Commands.TEXT + " TEXT"
                    + ");");
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_SN);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_CMD);
            onCreate(db);
        }

    }

    private DatabaseHelper dbh;

    @Override
    public boolean onCreate() {
        dbh = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        switch(uriMatcher.match(uri)) {
        case SN:
        {
            qb.setTables(TABLE_SN);
            qb.setProjectionMap(snpm);
            orderBy = SerialNumbers.DEFAULT_SORT_ORDER;
        }
        break;

        case SN_ID:
        {
            qb.setTables(TABLE_SN);
            qb.setProjectionMap(snpm);
            qb.appendWhere(SerialNumbers._ID + " = " + uri.getPathSegments().get(1));
            orderBy = SerialNumbers.DEFAULT_SORT_ORDER;
        }
        break;
        case CMD:
        {
            qb.setTables(TABLE_CMD);
            qb.setProjectionMap(cmdpm);
            orderBy = Commands.DEFAULT_SORT_ORDER;
        }
        break;

        case CMD_ID:
        {
            qb.setTables(TABLE_CMD);
            qb.setProjectionMap(cmdpm);
            qb.appendWhere(Commands._ID + " = " + uri.getPathSegments().get(1));
            orderBy = Commands.DEFAULT_SORT_ORDER;
        }
        break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if(!TextUtils.isEmpty(sortOrder)) {
            orderBy = sortOrder;
        }

        SQLiteDatabase db = dbh.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch(uriMatcher.match(uri)) {
        case SN:
            return SerialNumbers.CONTENT_TYPE;

        case SN_ID:
            return SerialNumbers.CONTENT_ITEM_TYPE;

        case CMD:
            return Commands.CONTENT_TYPE;

        case CMD_ID:
            return Commands.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        Uri baseUri;
        String table;
        String nullColumnHack;
        ContentValues values;
        if(uriMatcher.match(uri) == SN) {
            baseUri = SerialNumbers.CONTENT_URI;
            table = TABLE_SN;
            nullColumnHack = SerialNumbers.TEXT;
            if(initialValues != null)
                values = new ContentValues(initialValues);
            else
                values = new ContentValues();

            if(!values.containsKey(SerialNumbers.TEXT))
                throw new IllegalArgumentException("Text required");
        } else if(uriMatcher.match(uri) == CMD) {
            baseUri = Commands.CONTENT_URI;
            table = TABLE_CMD;
            nullColumnHack = Commands.TEXT;
            if(initialValues != null)
                values = new ContentValues(initialValues);
            else
                values = new ContentValues();

            if(!values.containsKey(Commands.TEXT))
                throw new IllegalArgumentException("Text required");
        } else {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = dbh.getWritableDatabase();
        long rowId = db.insert(table, nullColumnHack, values);
        if(rowId > 0) {
            Uri newUri = ContentUris.withAppendedId(baseUri, rowId);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbh.getWritableDatabase();
        int count;
        switch(uriMatcher.match(uri)) {
        case SN:
        {
            count = db.delete(TABLE_SN, where, whereArgs);
        }
        break;

        case SN_ID:
        {
            String msgId = uri.getPathSegments().get(1);
            count = db.delete(TABLE_SN, SerialNumbers._ID + " = " + msgId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); 
        }
        break;
        case CMD:
        {
            count = db.delete(TABLE_CMD, where, whereArgs);
        }
        break;

        case CMD_ID:
        {
            String msgId = uri.getPathSegments().get(1);
            count = db.delete(TABLE_CMD, Commands._ID + " = " + msgId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); 
        }
        break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = dbh.getWritableDatabase();
        int count;
        switch(uriMatcher.match(uri)) {
        case SN:
        {
            count = db.update(TABLE_SN, values, where, whereArgs);
        }
        break;

        case SN_ID:
        {
            String msgId = uri.getPathSegments().get(1);
            count = db.update(TABLE_SN, values, SerialNumbers._ID + " = " + msgId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); 
        }
        break;
        case CMD:
        {
            count = db.update(TABLE_CMD, values, where, whereArgs);
        }
        break;

        case CMD_ID:
        {
            String msgId = uri.getPathSegments().get(1);
            count = db.update(TABLE_CMD, values, Commands._ID + " = " + msgId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); 
        }
        break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(Data.AUTHORITY, "sn", SN);
        uriMatcher.addURI(Data.AUTHORITY, "sn/#", SN_ID);
        uriMatcher.addURI(Data.AUTHORITY, "cmd", CMD);
        uriMatcher.addURI(Data.AUTHORITY, "cmd/#", CMD_ID);

        snpm = new HashMap<String, String>();
        snpm.put(SerialNumbers._ID, SerialNumbers._ID);
        snpm.put(SerialNumbers.TEXT, SerialNumbers.TEXT);

        cmdpm = new HashMap<String, String>();
        cmdpm.put(Commands._ID, Commands._ID);
        cmdpm.put(Commands.TEXT, Commands.TEXT);
    }
}

Data.java

package org.frxstrem.xend;
import android.net.Uri;
import android.provider.BaseColumns;
public class Data {

    public static final String AUTHORITY = "org.frxstrem.xsend";

    private Data() { }

    public static class SerialNumbers implements BaseColumns {

        private SerialNumbers() { }

        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/sn");
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.frxstrem.serialnumber";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.frxstrem.serialnumber";

        public static final String DEFAULT_SORT_ORDER = "_id ASC";

        public static final String TEXT = "text";

    }

    public static class Commands implements BaseColumns {

        private Commands() { }
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/cmd");
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.frxstrem.command";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.frxstrem.command";

        public static final String DEFAULT_SORT_ORDER = "_id ASC";

        public static final String TEXT = "text";

    }
}

2 个答案:

答案 0 :(得分:10)

我自己想出来,使用以下代码:

Cursor c = getContentResolver().query(CONTENT_URI, null, DATA_FIELD + " = " + DatabaseUtils.sqlEscapeString(data), null, null);
if(c.getCount() == 0) {
  // not found in database
}

答案 1 :(得分:1)

在ContentResolver.query()中查找内容提供程序中的数据的方法。您将查询的具体内容取决于内容提供商,因此不知道很难说更多内容。