Android高效AsyncTask

发布于 2024-12-04 03:50:19 字数 1843 浏览 1 评论 0原文

我有一个 EditText,用户可以在其中输入公司名称。我在此 EditText 下方还有一个 ListView,它建议用户了解已添加到数据库中的内容...

<EditText android:id="@+id/txtBusinessName" android:hint="Name of Business" />
<ListView android:id="@+id/suggestionList" 
   android:layout_width="fill_parent" android:layout_height="wrap_content">
</ListView>

现在,当用户输入时,我会检查他们在数据库中输入的关键字,并检索必须在数据库中向用户显示的内容。列表视图。目前,在触发的每个按键事件中,我都以这种方式调用一个新的 AsyncTask...

        EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName);
                txtBusinessName.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (event.getAction() == KeyEvent.ACTION_UP) {
                            if (v instanceof EditText) {
                                EditText txtBusinessName = ((EditText) v);

                                if (txtBusinessName.length() > 0) {
                                   if (suggestionTask != null) {
                                    suggestionTask.cancel(true);
                                    suggestionTask = null;
                                   }
                                   suggestionTask = new GetCompaniesByKeywordAsyncTask(
                                        AddBusinessActivity.this, s);
                                   suggestionTask.execute(txtBusinessName.getText()
                                        .toString());
                                }
                            }
                        }
                        return false;
                    }
                });

有没有办法我只有一个 AsyncTask 实例,并要求它在用户在 EditText 中键入时检索名称?因为创建太多AsyncTask效率不高,最终会出现异常。我将在收到名称后填充 ListView,我可以要求 ListView 根据其中的内容重新调整自身大小吗?

I have an EditText where user can type in the name of the business. I also have a ListView below this EditText which suggest user about what is already added to the database...

<EditText android:id="@+id/txtBusinessName" android:hint="Name of Business" />
<ListView android:id="@+id/suggestionList" 
   android:layout_width="fill_parent" android:layout_height="wrap_content">
</ListView>

Now as user types in, I check for the keyword they typed, in the database and retrieve what it has to show the user in a ListView. Currently on every key up event fired, I am calling a new AsyncTask this way...

        EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName);
                txtBusinessName.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (event.getAction() == KeyEvent.ACTION_UP) {
                            if (v instanceof EditText) {
                                EditText txtBusinessName = ((EditText) v);

                                if (txtBusinessName.length() > 0) {
                                   if (suggestionTask != null) {
                                    suggestionTask.cancel(true);
                                    suggestionTask = null;
                                   }
                                   suggestionTask = new GetCompaniesByKeywordAsyncTask(
                                        AddBusinessActivity.this, s);
                                   suggestionTask.execute(txtBusinessName.getText()
                                        .toString());
                                }
                            }
                        }
                        return false;
                    }
                });

Is there a way I just have a single instance of AsyncTask and ask it to retrieve the names as user types in the EditText? Because creating too many AsyncTask isn't efficient and will end up in exception. I will populate the ListView upon receiving the names, can I ask ListView to re-size itself based on content inside it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

将军与妓 2024-12-11 03:50:19

为了制作单个AsyncTask,您需要重构AsyncTask以基于请求队列来运行。队列包含您要处理的所有关键字。然后,您可以在侦听器外部运行此 AsyncTask 一次,并添加 OnKeylistener 中的关键字。

为了更新ListView,我们将利用onProgressUpdate,它将根据doInBackground的结果更新ListView。

修改AsyncTask的骨架代码


    @Override
    protected Integer doInBackground(Void... params) {
        int errorCode = 0;

        try {
            // while running in the context of your activity
            // you should set this boolean to false once you have leave the activity
            while(!isRunning){
                // blocking call to get the next keyword that is added to the queue
                String responseData = getNextKeyword();

                // once you get the next keyword, you publish the progress
                // this would be executed in the UI Thread and basically would update the ListView
                publishProgress(responseData);
            }
        } catch(Exception e) {
            // error handling code that assigns appropriate error code
        }

        return errorCode;

    }

    @Override
    protected void onPostExecute(Integer errorCode) {
        // handle error on UI Thread based on errorCode
    }

    @Override
    protected void onProgressUpdate(String... values) {
        String searchKeyword = values[0];

        // handle the searchKeyword here by updating the listView
    }

    /***
     * Stub code for illustration only
     * Get the next keyword from the queue
     * @return The next keyword in the BlockingQueue
     */
    private String getNextKeyword() {
        return null;
    }

    /***
     * Stub code for illustration only
     * Add new keyword to the queue, this is called from the onKey method
     * @param keyword
     */
    public void addKeyword(String keyword) {
        // add the keyword to the queue
    }

然后你的代码被粗略地修改为:


// instantiate AsyncTask once
suggestionTask = new GetCompaniesByKeywordAsyncTask(
        AddBusinessActivity.this, s);

// run only one AsyncTask that is waiting for any keyword in the queue
suggestionTask.execute();

EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName);
txtBusinessName.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (v instanceof EditText) {
                EditText txtBusinessName = ((EditText) v);

                if (txtBusinessName.length() > 0) {
                   // add new keyword to the queue for processing
                   suggestionTask.addKeyword(txtBusinessName.getText()
                        .toString());
                }
            }
        }
        return false;
    }
});

In order to make a single AsyncTask, you need restructure the AsyncTask to run based on the request queue. The queue is containing all the keywords that you want to process. You would then run this AsyncTask outside of the listener once and add the keyword from the OnKeylistener.

To update the ListView, we will utilize onProgressUpdate that will update the ListView based on the result in doInBackground

The skeleton code for the modification AsyncTask


    @Override
    protected Integer doInBackground(Void... params) {
        int errorCode = 0;

        try {
            // while running in the context of your activity
            // you should set this boolean to false once you have leave the activity
            while(!isRunning){
                // blocking call to get the next keyword that is added to the queue
                String responseData = getNextKeyword();

                // once you get the next keyword, you publish the progress
                // this would be executed in the UI Thread and basically would update the ListView
                publishProgress(responseData);
            }
        } catch(Exception e) {
            // error handling code that assigns appropriate error code
        }

        return errorCode;

    }

    @Override
    protected void onPostExecute(Integer errorCode) {
        // handle error on UI Thread based on errorCode
    }

    @Override
    protected void onProgressUpdate(String... values) {
        String searchKeyword = values[0];

        // handle the searchKeyword here by updating the listView
    }

    /***
     * Stub code for illustration only
     * Get the next keyword from the queue
     * @return The next keyword in the BlockingQueue
     */
    private String getNextKeyword() {
        return null;
    }

    /***
     * Stub code for illustration only
     * Add new keyword to the queue, this is called from the onKey method
     * @param keyword
     */
    public void addKeyword(String keyword) {
        // add the keyword to the queue
    }

Then your code is rougly modified to:


// instantiate AsyncTask once
suggestionTask = new GetCompaniesByKeywordAsyncTask(
        AddBusinessActivity.this, s);

// run only one AsyncTask that is waiting for any keyword in the queue
suggestionTask.execute();

EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName);
txtBusinessName.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (v instanceof EditText) {
                EditText txtBusinessName = ((EditText) v);

                if (txtBusinessName.length() > 0) {
                   // add new keyword to the queue for processing
                   suggestionTask.addKeyword(txtBusinessName.getText()
                        .toString());
                }
            }
        }
        return false;
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文