在自定义内容提供程序中调用delete方法

时间:2011-03-10 23:46:29

标签: android android-contentprovider android-contentresolver onlongclicklistener

我正在学习Android,而且我遇到了涉及调用自定义内容提供商的问题。我一直在教学书中使用一个例子,虽然它描述了如何创建自定义提供者,但没有明确的例子如何调用其中的特定方法。我正在专门研究如何从自定义内容提供程序中删除单个记录。

以下是自定义内容提供商的代码(EarthquakeProvider.java):

@Override


public int delete(Uri uri, String where, String[] whereArgs) {
int count;

switch (uriMatcher.match(uri)) {
  case QUAKES:
    count = earthquakeDB.delete(EARTHQUAKE_TABLE, where, whereArgs);
    break;

  case QUAKE_ID:
    String segment = uri.getPathSegments().get(1);
    count = earthquakeDB.delete(EARTHQUAKE_TABLE, KEY_ID + "="
                                + segment
                                + (!TextUtils.isEmpty(where) ? " AND (" 
                                + where + ')' : ""), whereArgs);
    break;

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

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


 }

我试图从主活动中调用delete方法来删除单个条目,而不是整个数据库。我想对主活动的数组列表视图中显示的所选记录使用OnLongClickListener

到目前为止,我已经提出了这个方法的主要活动:

earthquakeListView.setOnItemLongClickListener(new OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(AdapterView _av, View _v, int _index,
            long arg3) {
        ContentResolver cr = getContentResolver();
        cr.delete(earthquakeProvider.CONTENT_URI, null, null); 

        return false;
    }

我知道上面的代码不起作用,但这与我目前的理解情况一样接近。

对此的任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:26)

cr.delete(earthquakeProvider.CONTENT_URI, null, null);

这是你的问题。首先,一些背景:

内容URI:(source

content://authority/path/##

最后的数字是可选的。如果存在,则URI引用数据库中的特定行,其中row._id =(数字)。如果不存在,则将该表作为一个整体引用。

delete()调用接受一个URI,一个where子句和一组被替换的字符串。例如:假设你有一个人数据库。

cr.delete(
   Person.CONTENT_URI, 
   "sex=? AND eyecolor=?", 
   new String[]{"male", "blue"});

将搜索整个人表,并删除性别为男性且眼睛颜色为蓝色的任何人。

如果where子句和where值为null,则delete()调用将匹配表中的每一行。这会导致您看到的行为。

有两种方法可以指定所需的行:

第一个选项,您可以将数字附加到URI:

cr.delete(
    EarthquakeProvider.CONTENT_URI.buildUpon().appendPath(String.valueOf(_id)).build(),
    null, null);

这会将URI限制为特定行,路径将通过您的case QUAKE_ID:语句,因此无论如何都只会删除一行。

第二个选项,您可以使用where子句:

cr.delete(EarthquakeProvider.CONTENT_URI, "_id=?", String.valueOf(_id)));

无论哪种方式,您都可以根据需要将删除限制为单行。后者使得代码更漂亮,但由于ContentProvider和ContentObservers的工作方式,前者更有效。

最后一点:在您的ContentProvider中,您需要添加一个电话 ContentResolver.notifyChange(Uri uri,ContentObserver observer,boolean syncToNetwork)。这有助于通知游标重新获取数据库查询,并通过自动化帮助解决很多问题。

相关问题