为什么我在使用ContentResolver.update时无法获得正确的结果?

时间:2015-02-27 08:07:00

标签: android android-contentprovider

我最近在android.I中学习了内容提供程序。我试图实现ContentProvider。当我执行更新时,感觉更像是删除而不是更新。

public void updateBook(Context context){
    String name=edName.getText().toString();
    String isbn=edIsbn.getText().toString();
    String author=edAuthor.getText().toString();
    //String msg="name:"+name+",isbn:"+isbn+",authro"+author;
    String tag="Exercise BookProvider";
    Log.d(tag, "updating a book");
    ContentValues cv=new ContentValues();
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, name);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_ISBN, isbn);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, author);

    ContentResolver cr=context.getContentResolver();
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Uri updateUri=Uri.withAppendedPath(uri, Integer.toString(4));
    Log.d(tag, "update uri:"+updateUri);
    int count=cr.update(updateUri, cv, null, null);

    Log.d(tag, "updated count:"+count);
}

Befor我跑了这个,已经有一本书的ID为4.更新计数返回1.但是当我试图调用show_books方法时,书4就消失了。它返回了所有没有书的书.I&#39 ;我将为我的测试活动提供完整的代码。

public class TestBookProvider extends Activity{

EditText edName,edAuthor,edIsbn;
Button addBtn,delBtn,updateBtn,showBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bookprovider);
    edName=(EditText) findViewById(R.id.edName);
    edAuthor=(EditText) findViewById(R.id.edAuthor);
    edIsbn=(EditText) findViewById(R.id.edIsbn);

    addBtn=(Button) findViewById(R.id.addBtn);
    delBtn=(Button) findViewById(R.id.delBtn);
    updateBtn=(Button) findViewById(R.id.updateBtn);
    showBtn=(Button)findViewById(R.id.showBtn);
}
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    addBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            addBook(TestBookProvider.this);
            //Toast.makeText(TestBookProvider.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
    showBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            showBooks(TestBookProvider.this);
        }
    });
    delBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            removeBook(TestBookProvider.this);
        }
    });
    updateBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            updateBook(TestBookProvider.this);
        }
    });
}
public void updateBook(Context context){
    String name=edName.getText().toString();
    String isbn=edIsbn.getText().toString();
    String author=edAuthor.getText().toString();
    //String msg="name:"+name+",isbn:"+isbn+",authro"+author;
    String tag="Exercise BookProvider";
    Log.d(tag, "updating a book");
    ContentValues cv=new ContentValues();
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, name);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_ISBN, isbn);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, author);

    ContentResolver cr=context.getContentResolver();
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Uri updateUri=Uri.withAppendedPath(uri, Integer.toString(3));
    Log.d(tag, "update uri:"+updateUri);
    int count=cr.update(updateUri, cv, null, null);

    Log.d(tag, "updated count:"+count);
}
public void addBook(Context context){
    String name=edName.getText().toString();
    String isbn=edIsbn.getText().toString();
    String author=edAuthor.getText().toString();
    //String msg="name:"+name+",isbn:"+isbn+",authro"+author;
    String tag="Exercise BookProvider";
    Log.d(tag, "adding a book");
    ContentValues cv=new ContentValues();
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, name);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_ISBN, isbn);
    cv.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, author);

    ContentResolver cr=context.getContentResolver();
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Log.d(tag, "book insert uri:"+uri);
    Uri insertedUri=cr.insert(uri, cv);
    Log.d(tag, "inserted uri:"+insertedUri);

}
public void removeBook(Context context){
    String tag="Exercise BookProvider";
    Log.d(tag, "remove a book");
    int i=getCount(context);
    ContentResolver cr=context.getContentResolver();
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Uri delUri=Uri.withAppendedPath(uri, Integer.toString(i));
    Log.d(tag, "del uri:"+delUri);
    cr.delete(delUri, null, null);
    Log.d(tag, "new count:"+getCount(context));
}
private int getCount(Context context){
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Activity a=(Activity)context;
    Cursor c=a.managedQuery(uri, null, null, null, null);
    int numberOfRecords=c.getCount();
    c.close();
    return numberOfRecords;
}
public void showBooks(Context context){
    String tag="Exercise BookProvider";
    Uri uri=BookProviderMetaData.BookTableMetaData.CONTENT_URI;
    Activity a=(Activity)context;
    Cursor c=a.managedQuery(uri, null, null, null, null);
    int iname=c.getColumnIndex(BookProviderMetaData.BookTableMetaData.BOOK_NAME);
    int iisbn=c.getColumnIndex(BookProviderMetaData.BookTableMetaData.BOOK_ISBN);
    int iauthor=c.getColumnIndex(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR);
    Log.d(tag, "name,isbn,author:"+iname+iisbn+iauthor);
    for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
        String id=c.getString(1);
        String name=c.getString(iname);
        String isbn=c.getString(iisbn);
        String author=c.getString(iauthor);
        StringBuffer buf=new StringBuffer(id);
        buf.append(",").append(name);
        buf.append(",").append(isbn);
        buf.append(",").append(author);
        Log.d(tag, buf.toString());
    }
    int numberOfRecords=c.getCount();
    Log.d(tag, "num of records:"+numberOfRecords);
    c.close();
}

}

这是我的bookProvider

public class BookProvider extends ContentProvider {
private static final String TAG = "BookProvider";
private static HashMap<String, String> sBooksProjectionMap;
static {
    sBooksProjectionMap = new HashMap<String, String>();
    sBooksProjectionMap.put(BookTableMetaData._ID, BookTableMetaData._ID);
    sBooksProjectionMap.put(BookTableMetaData.BOOK_NAME,
            BookTableMetaData.BOOK_NAME);
    sBooksProjectionMap.put(BookTableMetaData.BOOK_ISBN,
            BookTableMetaData.BOOK_ISBN);
    sBooksProjectionMap.put(BookTableMetaData.BOOK_AUTHOR,
            BookTableMetaData.BOOK_AUTHOR);
    sBooksProjectionMap.put(BookTableMetaData.CREATED_DATE,
            BookTableMetaData.CREATED_DATE);
    sBooksProjectionMap.put(BookTableMetaData.MODIFIED_DATE,
            BookTableMetaData.MODIFIED_DATE);
}
private static final UriMatcher sUriMatcher;
private static final int INCOMING_BOOK_COLLECTION_URI_INDICATOR = 1;
private static final int INCOMING_SINGLE_BOOK_URI_INDICATOR = 2;
static {
    sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    sUriMatcher.addURI(BookProviderMetaData.AUTHORITY, "books",
            INCOMING_BOOK_COLLECTION_URI_INDICATOR);
    sUriMatcher.addURI(BookProviderMetaData.AUTHORITY, "books/#",
            INCOMING_SINGLE_BOOK_URI_INDICATOR);

}

private static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, BookProviderMetaData.DATABASE_NAME, null,
                BookProviderMetaData.DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        Log.d(TAG, "inner oncreated called");
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + BookTableMetaData.TABLE_NAME);
        sql.append("(");
        sql.append(BookTableMetaData._ID + " INTEGER PRIMARY KEY,");
        sql.append(BookTableMetaData.BOOK_NAME + " TEXT,");
        sql.append(BookTableMetaData.BOOK_ISBN + " TEXT,");
        sql.append(BookTableMetaData.BOOK_AUTHOR + " TEXT,");
        sql.append(BookTableMetaData.CREATED_DATE + " INTEGER,");
        sql.append(BookTableMetaData.MODIFIED_DATE + " INTEGER ");
        sql.append(");");
        db.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.d(TAG, "inner onupgrade called");
        Log.w(TAG, "upgrading database from version " + oldVersion + " to "
                + newVersion + " ,which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + BookTableMetaData.TABLE_NAME);
        onCreate(db);
    }

}

private DatabaseHelper mOpenHelper;

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    // TODO Auto-generated method stub
    SQLiteDatabase db=mOpenHelper.getWritableDatabase();
    int count;
    switch (sUriMatcher.match(uri)) {
    case INCOMING_BOOK_COLLECTION_URI_INDICATOR:
        count=db.delete(BookTableMetaData.TABLE_NAME, where, whereArgs);
        break;
    case INCOMING_SINGLE_BOOK_URI_INDICATOR:
        String rowId=uri.getPathSegments().get(1);
        count=db.delete(BookTableMetaData.TABLE_NAME, BookTableMetaData._ID+"="+rowId+(!TextUtils.isEmpty(where)? " AND ("+where+")": ""), whereArgs);

        break;
    default:
        throw new IllegalArgumentException("unknown uri "+uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

@Override
public String getType(Uri uri) {
    // TODO Auto-generated method stub
    switch (sUriMatcher.match(uri)) {
    case INCOMING_BOOK_COLLECTION_URI_INDICATOR:
        return BookTableMetaData.CONTENT_TYPE;
    case INCOMING_SINGLE_BOOK_URI_INDICATOR:
        return BookTableMetaData.CONTENT_ITEM_TYPE;

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

}

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    // TODO Auto-generated method stub
    if (sUriMatcher.match(uri) != INCOMING_BOOK_COLLECTION_URI_INDICATOR) {
        throw new IllegalArgumentException("unknown uri " + uri);
    }
    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }
    Long now = Long.valueOf(System.currentTimeMillis());
    if (!values.containsKey(BookTableMetaData.CREATED_DATE)) {
        values.put(BookTableMetaData.CREATED_DATE, now);
    }
    if (!values.containsKey(BookTableMetaData.MODIFIED_DATE)) {
        values.put(BookTableMetaData.MODIFIED_DATE, now);
    }
    if (!values.containsKey(BookTableMetaData.BOOK_NAME)) {
        throw new SQLException(
                "Failed to insert row because Book Name is Needed " + uri);
    }
    if (!values.containsKey(BookTableMetaData.BOOK_ISBN)) {
        values.put(BookTableMetaData.BOOK_ISBN, "unknown isbn");
    }
    if (!values.containsKey(BookTableMetaData.BOOK_AUTHOR)) {
        values.put(BookTableMetaData.BOOK_AUTHOR, "unknown author");
    }
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId = db.insert(BookTableMetaData.TABLE_NAME,
            BookTableMetaData.BOOK_NAME, values);
    if (rowId > 0) {
        Uri insertedBookUri = ContentUris.withAppendedId(
                BookTableMetaData.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(insertedBookUri,
                null);
        return insertedBookUri;
    }
    throw new SQLException("failed to insert row into " + uri);
}

@Override
public boolean onCreate() {
    // TODO Auto-generated method stub
    Log.d(TAG, "main onCreate called");
    mOpenHelper = new DatabaseHelper(getContext());
    return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
    // TODO Auto-generated method stub
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    switch (sUriMatcher.match(uri)) {
    case INCOMING_BOOK_COLLECTION_URI_INDICATOR:
        qb.setTables(BookTableMetaData.TABLE_NAME);
        qb.setProjectionMap(sBooksProjectionMap);
        break;
    case INCOMING_SINGLE_BOOK_URI_INDICATOR:
        qb.setTables(BookTableMetaData.TABLE_NAME);
        qb.setProjectionMap(sBooksProjectionMap);
        qb.appendWhere(BookTableMetaData._ID + "="
                + uri.getPathSegments().get(1));
        break;
    default:
        throw new IllegalArgumentException("UNKNOWN URI " + uri);

    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder)) {
        orderBy = BookTableMetaData.DEFAULT_SORT_ORDER;
    } else {
        orderBy = sortOrder;
    }
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null,
            null, orderBy);
    int i = c.getCount();
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    // TODO Auto-generated method stub
    SQLiteDatabase db=mOpenHelper.getWritableDatabase();
    int count;
    switch (sUriMatcher.match(uri)) {
    case INCOMING_BOOK_COLLECTION_URI_INDICATOR:
        count=db.update(BookTableMetaData.TABLE_NAME, values, where, whereArgs);
        break;
    case INCOMING_SINGLE_BOOK_URI_INDICATOR:
        String rowId=uri.getPathSegments().get(1);
        count=db.delete(BookTableMetaData.TABLE_NAME, BookTableMetaData._ID+"="+rowId+(!TextUtils.isEmpty(where)? " AND ("+where+")": ""), whereArgs);
        break;
    default:
        throw new IllegalArgumentException("unknown uri "+uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

} 这是BookProviderMetaData

public class BookProviderMetaData {
public static final String AUTHORITY="com.flowers.provider.BookProvider";
public static final String DATABASE_NAME="book.db";
public static final int DATABASE_VERSION=1;
public static final String BOOKS_TABLE_NAME="books";

public BookProviderMetaData(){

}
public static final class BookTableMetaData implements BaseColumns{
    private BookTableMetaData(){

    }
    public static final String TABLE_NAME="books";
    public static final Uri CONTENT_URI=Uri.parse("content://"+AUTHORITY+"/books");
    public static final String CONTENT_TYPE="vnd.android.cursor.dir/vnd.flowers.book";
    public static final String CONTENT_ITEM_TYPE="vnd.android.cursor.item/vnd.flowers.book";
    public static final String DEFAULT_SORT_ORDER="modified DESC";
    public static final String BOOK_NAME="name";
    public static final String BOOK_ISBN="isbn";
    public static final String BOOK_AUTHOR="author";
    public static final String CREATED_DATE="created";
    public static final String MODIFIED_DATE="modified";
}

}

如果我错过了任何请,请不要犹豫告诉我!〜

1 个答案:

答案 0 :(得分:0)

在更新方法中,对于INCOMING_SINGLE_BOOK_URI_INDICATOR,您实际上是在调用SqLiteDatabase.delete,而不是更新。这看起来很奇怪,类似于你所描述的问题。你打算在这里打电话给更新吗?