使用Android内容提供商插入一行

时间:2016-11-05 16:45:40

标签: android android-contentprovider

我有下一个内容提供商 要在表AGENDA中插入一行,我执行:

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

}

1 个答案:

答案 0 :(得分:1)

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

// 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);