简体   繁体   English

如何运行多个 AsyncTask?

[英]How to run multiple AsyncTask?

I have 2 spinner, each spinner's data loaded from database using AsyncTask我有 2 个微调器,每个微调器的数据使用 AsyncTask 从数据库加载

i call the AsyncTasks using this我用这个调用 AsyncTasks

new PopulateSpinnerA().execute();

it works if i only call one AsyncTask for one Spinner如果我只为一个 Spinner 调用一个 AsyncTask,它就可以工作

BUT!但!

i have 2 Spinners, so i call the AsyncTask for each Spinner like this我有 2 个 Spinner,所以我像这样为每个 Spinner 调用 AsyncTask

new PopulateSpinnerA().execute(); // for Spinner A
new PopulateSpinnerB().execute(); // for Spinner B

I run it and my app force close我运行它并且我的应用程序强制关闭

solution?解决方案?

UPDATE!更新!

i get inspiration from someone below who answer with true and false我从下面回答真假的人那里得到灵感

im using a boolean (playing with true and false) to make my two spinners generated我使用 boolean(玩弄真假)来生成我的两个微调器

first i make a boolean variable首先我做一个 boolean 变量

Boolean SPN = false;

then i make a function to check the boolean and put it on onCreate() function然后我制作一个 function 来检查 boolean 并将其放在 onCreate() function

private void cek(){
        if(!SPN){
            new populateSpinnerA().execute();
        }
        if(SPN){
            new populateSpinnerB().execute();
        }
    }

on populateSpinnerA() i just put this 2 lines to run the second spinner's AsyncTask在 populateSpinnerA() 我只是把这 2 行来运行第二个微调器的 AsyncTask

SPN = true;
cek();

and

BOOM!繁荣!

it's done:D完成了:D

You can not have two spinner at a time.您不能同时拥有两个微调器。 Need to use any trick in this case,在这种情况下需要使用任何技巧,

  1. Use only one spinner.仅使用一个微调器。
  2. Start the spinner while initiating first spinner.在启动第一个微调器时启动微调器。
  3. Use one common flag set on PostExecute.使用 PostExecute 上设置的一个通用标志。
  4. Before step#3, on postExecute of both AsyncTask check the flag is already set, if yes just cancel the spinner.在第 3 步之前,在两个 AsyncTask 的 postExecute 上检查标志是否已设置,如果是,则取消微调器。

Refer below pseudo code.参考下面的伪代码。

postExecute(){
      If(taskCompletedFlag == true){
            //Code to cancel the spinner.
            taskCompletedFlag = false;
      }else{
            taskCompledtedFlag = true;
      }
}

PS - In case you are not aware which AsyncTask will initiate first, you can use same mechanism over there. PS - 如果您不知道哪个 AsyncTask 将首先启动,您可以在那里使用相同的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM