使用ContentResolver查詢SD卡中特定的檔案

德超發表於2017-03-29

官方定義這個類的主要作用就是,這個類提供了app訪問內容模型,直譯就是內容解析者的意思,Android通過ContentProvider來實現應用程式間的內容共享,ContentResolver就是來對系統或者我們自定義的ContentProvider進行互動,通常我們用這個類訪問的是系統的一些資料,比如 獲取通訊錄,多媒體檔案,以及你想獲取的特定的檔案。

用法:通過getContentResolver()得到ContentResolver物件

然後呼叫它的query(uri,projection, selection, selectionArgs, sortOrder)方法來查詢,其實感覺和查詢資料庫操作差不多

首先uri代表你要查詢檔案的uri,比如音訊(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI)

視訊(MediaStore.Video.Media.EXTERNAL_CONTENT_URI)

通訊錄(ContactsContract.Contacts.CONTENT_URI)

如果你這裡想要查詢特定檔案的話,或者你不知道你要查詢的uri是什麼,Android提供了一個

MediaStore.Files.getContentUri("str"),就是這個Files類,原始碼解釋說這個就是呼叫(text,html等等這些檔案的)

projection:查詢的列,不過濾填null

selection:相當於資料庫的 where引數 不過濾填null

selectionArgs:如果selection中有?,這裡可以填寫實際值來代替? 沒有填null

sortOrder:查詢的結果按照什麼來排序 不過濾填null

query方法返回一個Cursor,然後進行解析,

最近正好在做一個需要查詢記憶體卡中所有txt檔案的東西,剛開始想的是使用遞迴遍歷,因為我是遍歷一個資料夾重新整理一次ui,然後導致ui重新整理太快,經常會拋

The content of the adapter has changed but ListView did not receive a notification. 這個異常,然後感覺還是老實的用系統提供的方法吧

貼一個我查詢sd卡中txt檔案的程式碼

ContentResolver resolver = this.getContentResolver();
//txt mime_type = text/plain
        Cursor cursor = resolver.query(MediaStore.Files.getContentUri("external"),null,"mime_type=\"text/plain\"", null, null);
        if (cursor != null){
            while (cursor.moveToNext()){
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE));
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
                int fileLength = cursor.getInt(cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE));
                //這裡新增自己想要進行的操作可以了
            }
        }


相關文章