Activity.managedQuery類應用

Activity.managedQuery()
獲取一個包含指定數據的 Cursor 對象,並由 Activity 來接管這個 Cursor 的生命週期。
首先該函數經過調用 getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder) 獲取一個包含指定數據(由 query 方法的參數指定)的 Cursor 對象。
而後經過調用 startManagingCursor(c) 實現由 Activity 來接管返回的 Cursor c 的生命週期。

原型:
public final Cursor managedQuery(Uri uri,
                                 String[] projection,
                                 String selection,
                                 String[] selectionArgs,
                                 String sortOrder)
{
    Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
    if (c != null) {
        startManagingCursor(c);
    }
    return c;
}
 
參數:
uri, 用於 Content Provider 查詢的 URI,也就是說從這個 URI 中獲取數據。
例如:
Uri uri = Contacts.People.CONTENT_URI;   //聯繫人列表URI。

projection, 用於標識 uri 中有哪些 columns 須要包含在返回的 Cursor 對象中。
例如:
//待查詢的columnsString[] projection = { 
     Contacts.PeopleColumns.NAME, 
     Contacts.PeopleColumns.NOTES 
};

selection, 做爲查詢的過濾參數(過濾出符合 selection 的數據),相似於 SQL 中 Where 語句以後的條件選擇。
例如:
String selection = Contacts.People.NAME + 「=?」 //查詢條件

selectionArgs, 查詢條件參數,配合 selection 參數使用。
例如:
String[] selectionArgs = {「Braincol」, 「Nixn.dev」};//查詢條件參數

sortOrder,查詢結果的排序方式(按查詢列( projection 參數中的 columns )中的某個 column )排序)。
例如:
String sortOrder = Contacts.PeopleColumns.NAME; //查詢結果的排序方式(按指定的查詢列排序)
 
返回值:
一個包含指定數據的 Cursor 對象。
 
示例:
Uri uri = Contacts.People.CONTENT_URI;
String[] projection = { Contacts.PeopleColumns.NAME,
   Contacts.PeopleColumns.NOTES 
        };
String selection = Contacts.PeopleColumns.NAME + "=?";
String[] selectionArgs = { "Braincol","Nixn.dev" };
String sortOrder = Contacts.PeopleColumns.NAME;
//使用 managedQuery 獲取 Contacts.People 這個 ContentProvider 的 Cursor。
Cursor cursor = managedQuery(uri, projection, selection, selectionArgs,sortOrder);
上述示例的含義就是:在聯繫人列表中查詢 NAME 爲 Braincol 和 Nixn.dev 兩個聯繫人的 "NAME" 和 "NOTES" 信息,而且將這些信息按照名字( NAME )排序,最後將排序以後的結果包裝在一個 Cursor 對象中返回。

android.content.ContentValues
保存將插入的單一記錄的值。ContentValues是一個鍵/值對字典。
例如:
//將記錄填充到ContentValues
ContentValues values = new ContentValues();
values.put("title","New note");
values.put("note","This is a new note");
//告訴android.content.ContentResolver使用URI插入記錄
ContentResolver contentResolver = new ContentResolver(); //獲取ContentResolver的引用
Uri newUri = contentResolver.insert(Notepad.notes.CONTENT_URI,values);//返回的newUri的結構:Notepad.notes.CONTENT_URI/new_id
//獲取對文件輸出流的引用
OutputStream outStream = contentResolver.openOutputStream(newUri);
someSourceBitmap.compress(Bitmap.CompressFormat.JEPG, 50, outStream);
outStream.close();
相關文章
相關標籤/搜索