如何查明内容提供商是否包含数据?

发布于 2024-11-14 04:54:25 字数 10654 浏览 0 评论 0原文

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

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";

    }
}

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;
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";

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拒绝两难 2024-11-21 04:54:25

我自己解决了这个问题,使用以下代码:

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

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
}
孤独岁月 2024-11-21 04:54:25

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文