开发者

How to find out if a content provider contains data?

So basically, I have this content provider which I use to store and retrieve some data in a database. In one of my activities, I have a function for adding data to this database; however, I do not want there to be duplicate entries. My function would look something like this:

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
  }
}

Now, my question is, how can I check whether or not the data is already stored by the content provider?

EDIT:

This is the code for my content provider:

DataProvider.java

package org.frxstrem.xend;
import java.util.HashMap;
import org.frxstrem.xend.Data.Commands;
import org.frxstrem.xend.Data.SerialNumbers;开发者_如何学JAVA
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";

    }
}


I figured it out myself, using the following code:

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


The way to find out about data in a content provider is with ContentResolver.query(). Exactly what you will query will depend on the content provider, so without knowing that it is hard to say much more.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜