provider的多表查询

我们都知道sqlite db里面会有是可以实现多个数据表联合查询,一直没有注意到provider是不能关连查询呢。今天看文档发现了一个不错的东西。写一个例子如下:

**
 * @title
 * @author LiYa
 * @version 1.0 Apr 25, 201210:40:58 AM
 */
public class TestcontactsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ContentResolver resolver = getContentResolver();
        Cursor cursor1 = resolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{Contacts._ID,Contacts.DISPLAY_NAME}, null, null, Contacts._ID);
        Cursor cursor2 = resolver.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{RawContacts.CONTACT_ID,RawContacts.ACCOUNT_NAME}, null, null, RawContacts.CONTACT_ID);
 
        CursorJoiner joiner = new CursorJoiner(cursor1, new String[]{Contacts._ID}, cursor2, new String[]{RawContacts.CONTACT_ID});
        for (CursorJoiner.Result joinerResult : joiner) {
            switch (joinerResult) {
                case LEFT:
                    // handle case where a row in cursorA is unique
                    break;
                case RIGHT:
                    // handle case where a row in cursorB is unique
                    break;
                case BOTH:
                    // handle case where a row with the same key is in both cursors
                    String name = cursor1.getString(cursor1.getColumnIndex(Contacts.DISPLAY_NAME));
                    String account = cursor2.getString(cursor2.getColumnIndex(RawContacts.ACCOUNT_NAME));
 
                    System.out.println("name :" + name + " account :" + account);
                    break;
            }
        }
    }
}

上面就可以查询多个表中的值了,如果要提供外部一个使用的cursor,那么就可以用MatrixCursor来处理下就可以了。

 

posted @ 2012-07-03 10:32  xianyuan  阅读(252)  评论(0编辑  收藏  举报