android - 如何在线程内使用 Cursor 进行查询? (安卓)

标签 android android-cursor android-cursorloader

我最近开始了我的第一个大学应用程序,作为我应用程序的一部分,我想使用 this guide. 访问手机的联系人。

在指南中,onActivityResult 看起来像这样:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request it is that we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // Get the URI that points to the selected contact
            Uri contactUri = data.getData();
            // We only need the NUMBER column, because there will be only one row in the result
            String[] projection = {Phone.NUMBER};

            // Perform the query on the contact to get the NUMBER column
            // We don't need a selection or sort order (there's only one result for the given URI)
            // CAUTION: The query() method should be called from a separate thread to avoid blocking
            // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
            // Consider using CursorLoader to perform the query.
            Cursor cursor = getContentResolver()
                    .query(contactUri, projection, null, null, null);
            cursor.moveToFirst();

            // Retrieve the phone number from the NUMBER column
            int column = cursor.getColumnIndex(Phone.NUMBER);
            String number = cursor.getString(column);

            // Do something with the phone number...
        }
    }
}

它说我应该使用线程或 CursorLoader 来执行查询,但到目前为止我无法为此找到好的解决方案。如果我将查询方法放在一个线程中,那么我就无法从中访问数据:

    Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        Cursor cursor = getContentResolver()
                                .query(contactUri, projection, null, null, null);
                    }
                };
                Thread queryThread = new Thread(r);
                queryThread.start();
cursor.moveToFirst();
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

因此在此代码中,Android Studio 无法解析符号“cursor”:( 到目前为止,我找不到关于如何使用 CursorLoaders 执行此操作的指南。

最佳答案

您可以使用 AsyncTask为了这份工作!

     class WorkCursor extends AsyncTask<Cursor,Object,String> {

            String[] projection;
            Uri contactUri;

            public WorkCursor(String[] projection,Uri contactUri){
                this.contactUri = contactUri;
                this.projection = projection;
            }


            @Override
            protected String doInBackground(Cursor... cursors) {

                //This is done in the background

                Cursor cursor = MyActivity.this.getContentResolver()
                        .query(contactUri, projection, null, null, null);

                int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String number = cursor.getString(column);

                return number;
            }

            @Override
            protected void onPostExecute(String number) {
                super.onPostExecute(number);

                //This is done on the UI thread
                functionCall(number);

            }
        }

        public void functionCall(String number){
            //This is the UI thread
            //You can do whatever you with your number
            Toast.makeText(this,"This is the number: "+number,Toast.LENGTH_SHORT).show();
        }

然后像这样调用Asynctask:

new WorkCursor(projection,contactUri).execute();

另一种方法是像您一样做,但在线程内完成所有工作,然后像这样在 UI 线程上运行结果:

new Thread(new Runnable() {
            @Override
            public void run() {
                Cursor cursor = getContentResolver()
                        .query(contactUri, projection, null, null, null);

                cursor.moveToFirst();
                int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                final String number = cursor.getString(column);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        functionCall(number);
                    }
                });
            }
        }).run();

字符串编号必须是最终的,以便在另一个(可在 UI 上运行的)线程中访问!

免责声明:代码未经测试。

关于android - 如何在线程内使用 Cursor 进行查询? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30934975/

相关文章:

java - Android自定义View——适配不同屏幕

android - 使用 SimpleCursorAdapter 从 Cursor 更改值

java - 如何测试 SQLiteDatabase 查询中的光标是否为空

java - 如何部分更新 Realm 对象

android - 错误 : java. lang.ClassNotFoundException : Didn't find class "com. google.firebase.firestore.local.SQLiteSchema

Android RecyclerView + CursorLoader + ContentProvider + "Load More"

android - CursorLoader结果选择

android - 管理加载器 ID 的唯一性

java - 轻松使用 CursorLoader

android - 如何批准 Android 应用程序的 Instagram Api 权限