在Android的多和重复的AsyncTask [英] Multiple and Repetitive AsyncTask in Android

查看:242
本文介绍了在Android的多和重复的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个AsyncTask的相互合作。我使用他们创造餐厅的菜单。第一个Web服务从数据库中获取菜单的标题。第二个Web服务获得冠军的项目从数据库中。我得到我的第一次的AsyncTask和项目数据的标题数据在我的第二个AsyncTask的。

例如,我有十个菜单标题。有八个项目为每个标题。我执行第一AsyncTask的,并得到所有菜单标题。我想打电话给在第一的AsyncTask的onPostExecute第二的AsyncTask为获得这个称号的项目,并添加TextView中。我分别要等完成了添加项目每秒钟任务。

总之,我需要先打电话AsyncTask的等待完成它。然后发送请求给第二AsyncTask的第一AsyncTask的。我要等待每个请求完成。我怎么能等吗?

下面是我的code。

第一的AsyncTask

 公共类BaslikDoldurAS延伸的AsyncTask<字符串,字符串[] []的String [] []> {
        INT ParamID;        公共BaslikDoldurAS(字符串ParamID){
            this.ParamID =的Integer.parseInt(ParamID);
        }        @覆盖
        保护的String [] [] doInBackground(字符串... PARAMS){
            BaslikDoldur(ParamID);
            返回sonuc;
        }        保护无效onPostExecute(字符串[] [] son​​uc){
            的for(int i = 0; I< baslikCount;我++){
                 MenuDoldurAS KONTROL =新MenuDoldurAS(firma_id,sonuc [2] [I]);
                 kontrol.execute();
            }
        }
    }

我的功能,它是第一个使用的AsyncTask

 私有String [] [] BaslikDoldur(整数ParamID){
        的PropertyInfo ID =新的PropertyInfo();
        id.name =ID;
        id.setValue(ParamID);
        id.type = PropertyInfo.INTEGER_CLASS;        SoapObject要求=新SoapObject(命名空间BaslikDoldur);
        request.addProperty(ID);
        SoapSerializationEnvelope信封=新SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut =请求;
        envelope.dotNet = TRUE;
        envelope.setOutputSoapObject(请求);        HttpTransportSE androidHttpTransport =新HttpTransportSE(MenuURL);
        androidHttpTransport.debug = TRUE;        尝试{            androidHttpTransport.call(http://tempuri.org/BaslikDoldur,信封);
            SoapObject响应=(SoapObject)envelope.getResponse();            sonuc [2] =新的String [response.getPropertyCount()]; // baslik
            baslikCount = response.getPropertyCount();            的for(int i = 0; I< response.getPropertyCount();我++){
                   对象属性= response.getProperty(I)
                   如果(财产的instanceof SoapObject){
                       SoapObject菜单=(SoapObject)财产;
                       sonuc [2] [I] = menu.getProperty(menu_baslik)的toString();
                   }
            }
     }
             赶上(例外五){
                e.printStackTrace();
            }
        返回sonuc;    }

二的AsyncTask

 公共类MenuDoldurAS延伸的AsyncTask<字符串,字符串[] []的String [] []> {
        INT ParamID;
        串Baslik;        公共MenuDoldurAS(字符串ParamID,字符串Baslik){
            this.ParamID =的Integer.parseInt(ParamID);
            this.Baslik = Baslik;
        }
        @覆盖
        保护的String [] [] doInBackground(字符串... PARAMS){
            MenuDoldur(ParamID,Baslik);
            返回sonuc;
        }        保护无效onPostExecute(字符串[] [] son​​uc){
            的for(int i = 0; I<计数;我++){
                串baslik =;
                如果(!baslik.equals(sonuc [2] [I])){
                    baslik = sonuc [2] [I];
                    TextView的basliktxt =新的TextView(Urun.this);
                    basliktxt.setText(sonuc [2] [I]);
                    basliktxt.setTextSize(20);
                    basliktxt.setTextColor(Color.RED);
                    basliktxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                    urunLayout.addView(basliktxt);
                }
                其他{
                    TextView的aciklamatxt =新的TextView(Urun.this);
                    aciklamatxt.setText(sonuc [3] [I]);
                    aciklamatxt.setTextColor(Color.parseColor(#0c0c7c));
                    aciklamatxt.setTextSize(17);
                    aciklamatxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                    urunLayout.addView(aciklamatxt);
                }
            }
        }    }

我的功能是在第二AsyncTask的使用

 私有String [] [] MenuDoldur(整数ParamID,字符串Baslik){
        的PropertyInfo ID =新的PropertyInfo();
        id.name =ID;
        id.setValue(ParamID);
        id.type = PropertyInfo.INTEGER_CLASS;        的PropertyInfo baslik =新的PropertyInfo();
        baslik.name =baslik;
        baslik.setValue(Baslik);
        baslik.type = PropertyInfo.STRING_CLASS;        SoapObject要求=新SoapObject(命名空间MenuDoldur);
        request.addProperty(ID);
        SoapSerializationEnvelope信封=新SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut =请求;
        envelope.dotNet = TRUE;
        envelope.setOutputSoapObject(请求);        HttpTransportSE androidHttpTransport =新HttpTransportSE(MenuURL);
        androidHttpTransport.debug = TRUE;        尝试{            androidHttpTransport.call(http://tempuri.org/MenuDoldur,信封);
            SoapObject响应=(SoapObject)envelope.getResponse();            sonuc [3] =新的String [response.getPropertyCount()]; // aciklama已经fiyat
            数= response.getPropertyCount();            的for(int i = 0; I< response.getPropertyCount();我++){
                   对象属性= response.getProperty(I)
                   如果(财产的instanceof SoapObject){
                       SoapObject菜单=(SoapObject)财产;
                       sonuc [3] [I] = menu.getProperty(menu_aciklama)的toString()+ - + menu.getProperty(menu_fiyat)的toString()。;
                   }
            }
     }
             赶上(例外五){
                e.printStackTrace();
            }
        返回sonuc;    }


解决方案

如果你想等到所有AsyncTasks都继续做之前,你为什么不干脆把所有你在第一个的AsyncTask的doInBackground工作?

或者你不想这样做,因为要并行运行10第二个任务? (顺便说一下你不这样做,无论如何,因为你没有使用THREAD_POOL执行人任务。)如果是这样的话,那么,为什么不只是做类似

  //变量都可以访问任务
ArrayList的<&AsyncTask的GT; mRunningTasks =新的ArrayList<&AsyncTask的GT;();
// AsyncTask1
保护无效onPostExecute(字符串[] [] son​​uc){
    的for(int i = 0; I< baslikCount;我++){
         MenuDoldurAS KONTROL =新MenuDoldurAS(firma_id,sonuc [2] [I]);
         mRunningTasks.add(KONTROL);
    }
    对于(AsyncTask的任务:mRunningTasks){
        task.execute();
    }
}// AsyncTask2
保护无效onPostExecute(...){
    布尔allComplete =真;
    对于(AsyncTask的任务:mRunningTasks){
      如果(!task.getStatus()。等于(AsyncTask.Status.FINISHED)){
          allComplete = FALSE;
          打破;
      }
    }
    如果(allComplete){
       //做什么
       mRunningTasks.clear();
    }
}

I have two asynctask working with each other. I'm using them for creating Restaurant menu. First web service gets menu's titles from database. Second web service gets items of title from database. I get title data in my first asynctask and item data in my second asynctask.

For example, I have ten menu titles. There are eight items for each title. I execute first asynctask and get all of menu titles. I want to call second asynctask in first asynctask's onPostExecute for get this title's item and add TextView. I have to wait finished every second task for add item respectively.

In short, I need call first AsyncTask and wait finish it. Then send request to second AsyncTask in First AsyncTask. I have to wait every request to finish. How can I wait ?

Here is the my code.

First AsyncTask

public class BaslikDoldurAS extends AsyncTask<String,String[][],String[][]>{
        int ParamID;

        public BaslikDoldurAS(String ParamID){
            this.ParamID=Integer.parseInt(ParamID);
        }

        @Override
        protected String[][] doInBackground(String... params) {
            BaslikDoldur(ParamID);
            return sonuc;
        }

        protected void onPostExecute(String[][] sonuc){
            for(int i=0;i<baslikCount;i++){ 
                 MenuDoldurAS kontrol = new MenuDoldurAS(firma_id,sonuc[2][i]);
                 kontrol.execute();
            } 
        }
    }

my function which is used in first asyncTask

private String[][] BaslikDoldur(Integer ParamID){
        PropertyInfo id = new PropertyInfo();
        id.name= "id";
        id.setValue(ParamID);
        id.type = PropertyInfo.INTEGER_CLASS;

        SoapObject request = new SoapObject(NAMESPACE, "BaslikDoldur");
        request.addProperty(id);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut=request;
        envelope.dotNet = true;     
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(MenuURL);
        androidHttpTransport.debug = true;

        try {

            androidHttpTransport.call("http://tempuri.org/BaslikDoldur", envelope);
            SoapObject response = (SoapObject) envelope.getResponse();

            sonuc[2]=new String[response.getPropertyCount()]; //baslik
            baslikCount=response.getPropertyCount();

            for(int i=0;i<response.getPropertyCount();i++){    
                   Object property = response.getProperty(i);
                   if(property instanceof SoapObject){
                       SoapObject menu = (SoapObject) property;
                       sonuc[2][i] = menu.getProperty("menu_baslik").toString();
                   }
            }
     } 
             catch (Exception e) {          
                e.printStackTrace();
            }
        return sonuc;

    }

Second AsyncTask

public class MenuDoldurAS extends AsyncTask<String,String[][],String[][]>{
        int ParamID;
        String Baslik;

        public MenuDoldurAS(String ParamID,String Baslik){
            this.ParamID=Integer.parseInt(ParamID);
            this.Baslik=Baslik;
        }
        @Override
        protected String[][] doInBackground(String... params) {
            MenuDoldur(ParamID,Baslik);
            return sonuc;
        }

        protected void onPostExecute(String[][] sonuc){
            for(int i=0;i<count;i++){
                String baslik="";
                if(!baslik.equals(sonuc[2][i])){
                    baslik=sonuc[2][i];
                    TextView basliktxt = new TextView(Urun.this);
                    basliktxt.setText(sonuc[2][i]);
                    basliktxt.setTextSize(20);
                    basliktxt.setTextColor(Color.RED);
                    basliktxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                    urunLayout.addView(basliktxt);
                }
                else{
                    TextView aciklamatxt = new TextView(Urun.this);
                    aciklamatxt.setText(sonuc[3][i]);
                    aciklamatxt.setTextColor(Color.parseColor("#0c0c7c"));
                    aciklamatxt.setTextSize(17);
                    aciklamatxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                    urunLayout.addView(aciklamatxt);
                }
            }   
        }

    }

my function which is used in second asyncTask

private String[][] MenuDoldur(Integer ParamID,String Baslik){
        PropertyInfo id = new PropertyInfo();
        id.name= "id";
        id.setValue(ParamID);
        id.type = PropertyInfo.INTEGER_CLASS;

        PropertyInfo baslik = new PropertyInfo();
        baslik.name= "baslik";
        baslik.setValue(Baslik);
        baslik.type = PropertyInfo.STRING_CLASS;

        SoapObject request = new SoapObject(NAMESPACE, "MenuDoldur");
        request.addProperty(id);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut=request;
        envelope.dotNet = true;     
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(MenuURL);
        androidHttpTransport.debug = true;

        try {

            androidHttpTransport.call("http://tempuri.org/MenuDoldur", envelope);
            SoapObject response = (SoapObject) envelope.getResponse();

            sonuc[3]=new String[response.getPropertyCount()]; //aciklama ve fiyat
            count = response.getPropertyCount();

            for(int i=0;i<response.getPropertyCount();i++){    
                   Object property = response.getProperty(i);
                   if(property instanceof SoapObject){
                       SoapObject menu = (SoapObject) property;
                       sonuc[3][i] = menu.getProperty("menu_aciklama").toString() + " - " + menu.getProperty("menu_fiyat").toString();
                   }
            }
     } 
             catch (Exception e) {          
                e.printStackTrace();
            }
        return sonuc;   

    }

解决方案

If you want to wait until all AsyncTasks are done before proceeding, why don't you just put all of you work in doInBackground of the first AsyncTask?

Or you don't want to do this because you want to run the 10 "second tasks" in parallel? (Which, incidentally you're not doing anyway, because you're not using the THREAD_POOL Executor for your tasks.) If this is the case then why not just do something like

// variable accessible to both tasks
ArrayList<AsyncTask> mRunningTasks = new ArrayList<AsyncTask>();
// AsyncTask1
protected void onPostExecute(String[][] sonuc){
    for(int i=0;i<baslikCount;i++){ 
         MenuDoldurAS kontrol = new MenuDoldurAS(firma_id,sonuc[2][i]);
         mRunningTasks.add(kontrol);
    }
    for (AsyncTask task : mRunningTasks) {
        task.execute();
    }
}

// AsyncTask2
protected void onPostExecute(...) {
    boolean allComplete = true;
    for (AsyncTask task : mRunningTasks) {
      if (!task.getStatus().equals(AsyncTask.Status.FINISHED)) {
          allComplete = false;
          break;
      }
    }
    if (allComplete) {
       //do whatever
       mRunningTasks.clear();
    }
}

这篇关于在Android的多和重复的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆