使用 Android Content Provider 插入一行

Inserting a row with Android Content Provider

我有下一个Content Provider 要在 Table 议程中插入一行,我这样做:

 ContentValues values = new ContentValues(1);
 values.put("MSG", "test");
  context.getContentResolver().insert(DataProvider.CONTENT_URI_AGENDA, values);

一切正常。

但是现在,我想使用带有 AGENDA_INSERTWITHCONFLICT 的 uri 来插入一行。 拜托,我该如何修改该行:

context.getContentResolver().insert(DataProvider.CONTENT_URI_AGENDA, values);

要做吗?

这是我的提供商:

public class DataProvider extends ContentProvider {
    public static final String TAGPROVIDER = "net.techabout.medappointment.provider";
    public static final Uri CONTENT_URI_AGENDA = Uri.parse("content://"+TAGPROVIDER+"/agenda");

    public static final String TABLE_AGENDA = "agenda";

    private DbHelper dbHelper;

    private static final int AGENDA_ALLROWS = 5;
    private static final int AGENDA_INSERTWITHCONFLICT=7;

    private static final UriMatcher uriMatcher;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(TAGPROVIDER, "agenda", AGENDA_ALLROWS);
        uriMatcher.addURI(TAGPROVIDER, "agenda", AGENDA_INSERTWITHCONFLICT);
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        long id;
        switch (uriMatcher.match(uri)) {
            case AGENDA_ALLROWS:
                id = db.insertOrThrow(TABLE_AGENDA, null, values);
                break;
            case AGENDA_INSERTWITHCONFLICT:
                  id=db.insertWithOnConflict(TABLE_AGENDA, BaseColumns._ID, values, SQLiteDatabase.CONFLICT_REPLACE);
                  break;

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

        Uri insertUri = ContentUris.withAppendedId(uri, id);
        getContext().getContentResolver().notifyChange(insertUri, null);
        return insertUri;
    }

}

进行以下更改,请根据需要使用命名约定。

// content provider
static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(TAGPROVIDER, "agenda", AGENDA_ALLROWS);
    uriMatcher.addURI(TAGPROVIDER, "agenda_insert_conflicts", AGENDA_INSERTWITHCONFLICT);
}

调用机制

 String URL = "net.techabout.medappointment.provider/agenda_insert_conflicts";

  Uri uri = Uri.parse(URL);
context.getContentResolver().insert(uri , values);