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

How to do a query with Cursor inside a thread? (android)

我最近开始了我的第一个大学应用程序,作为我应用程序的一部分,我想使用 this guide.

访问 phone 的联系人

在指南中,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 执行此操作的指南。

你好像不太明白什么叫单独开线程。在您的示例中,游标不仅超出了范围,而且它也是异步初始化的,这意味着它在您调用 start() 后不会立即可用。 start() 总是立即完成,只是导致线程稍后执行,而不会阻塞主线程。

在 android 中,对于大多数用例,使用 AsyncTask 最方便,而不是手动创建单独的线程。有关详细信息,请参阅 Processes and Threads guide

您可以使用 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 上可用)线程中访问!

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