Android AsyncTask - 执行后,如何更新视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10570243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:12:06  来源:igfitidea点击:

AsyncTask - after execution, how to update view?

androidandroid-asynctask

提问by richey

In the onCreate() event of an Activity, I have started an AsyncTask to retrieve Product data from a database. After this has been completed successfully, how can I update the display?

在 Activity 的 onCreate() 事件中,我启动了一个 AsyncTask 来从数据库中检索产品数据。成功完成后,如何更新显示?

Metacode:

元代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.venueviewbasic);
            (..)
    new GetProductDetails().execute();

class GetProductDetails extends AsyncTask<String, String, String> {

    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("id", vid));
        (.. retrieve and parse data and set new textview contents ..)

The textviews etc. don't get updated however.

然而,文本视图等不会更新。

回答by MAC

If you want to update the view from async after complete process in then you can use

如果要在完成过程后从异步更新视图,则可以使用

protected void onPostExecute(String result)
    {
        textView.setText(result);
    }

But if you want to update data while running background process then use. For ex...

但是,如果您想在运行后台进程时更新数据,请使用。对于前...

protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));<------
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {  <-------
         setProgressPercent(progress[0]);
     }

for more detail see this linkHope this will help you...!

有关更多详细信息,请参阅此链接希望这对您有所帮助...!

回答by Abhik

I am guessing the question is more about how to get hold of the UI View if the asyncTask is in a separate file .

我猜这个问题更多是关于如果 asyncTask 在一个单独的文件中,如何获取 UI 视图。

In that case you have to pass the context to the Async task and use that to get the view.

在这种情况下,您必须将上下文传递给 Async 任务并使用它来获取视图。

class MyAsyncTask extends AsyncTask<URL, Integer, Long> {

    Activity mActivity;

    public MyAsyncTask(Activity activity) {
       mActivity = ativity;
    }

And then in your onPostExecute use

然后在你的 onPostExecute 中使用

int id = mActivity.findViewById(...);

Remember you cannot update the View from "doInBackground" since its not the UI thread.

请记住,您不能从“doInBackground”更新视图,因为它不是 UI 线程。

回答by Tony the Pony

In your AsyncTaskclass, add a onPostExecutemethod. This method executes on the UI thread and can update any UI component.

在您的AsyncTask类中,添加一个onPostExecute方法。此方法在 UI 线程上执行并且可以更新任何 UI 组件。

class GetProductDetails extends AsyncTask<...> 
{
    ...
    private TextView textView;
    ...
    protected void onPostExecute(String result)
    {
        textView.setText(result);
    }
}

(The resultparameter is the value returned from the doInBackgroundmethod of your class.)

result参数是从doInBackground您的类的方法返回的值。)