【问题标题】:AsyncTask in a Loop In AndroidAndroid中循环中的AsyncTask
【发布时间】:2013-10-03 11:13:43
【问题描述】:

我正在创建一个应用程序,它将更新城市的天气详细信息。循环将是一个城市列表。所以我希望列表中有尽可能多的城市。我将使用 AsyncTask 方法发送请求并解析它。同时我正在膨胀一个布局,我必须将与城市相对应的所有天气详细信息放在布局中。我该如何实现这一点,请帮助我。

XML 我正在膨胀的文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/depart_details"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/flight_depart_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:padding="3dip"
        android:layout_marginTop="10dp"
        android:src="@drawable/f1" />

    <TextView
        android:id="@+id/depart_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/flight_depart_image"
        android:text=""
        android:textColor="#666666"
        android:textSize="25sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/depart_airport_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/depart_time"
        android:text=""
        android:textColor="#666666"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/depart_airport"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/depart_airport_city"
        android:layout_marginLeft="125dp"
        android:text="N/A"
        android:textColor="#666666"
        android:textSize="12sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/weather_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft ="40dp"
        android:layout_toRightOf="@+id/depart_airport"
        android:src="@drawable/image" />

    <TextView
        android:id="@+id/tempraturetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_toRightOf="@+id/weather_image"
        android:text="Temp:" />

    <TextView
        android:id="@+id/temprature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_toRightOf="@+id/tempraturetext"
        android:text="20℃" />

    <TextView
        android:id="@+id/humidity_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temprature"
        android:layout_marginLeft="3dp"
        android:layout_toRightOf="@+id/weather_image"
        android:text="Humidity:" />

    <TextView
        android:id="@+id/humidity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temprature"
        android:layout_marginLeft="3dp"
        android:layout_toRightOf="@+id/humidity_text"
        android:text="32" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/depart_airport"
        android:layout_marginTop="5dp"
        android:background="#d3d3d3" >
    </LinearLayout>

我创建这个函数来发送请求

private WeatherResponse requestWeatherUpdate(String location) {
        url = "" + location; //This location will be dyanamic and multiple
        Log.d("URL for Weather Upadate", url);
        WeatherUpdate weatherReq = new WeatherUpdate(new CallBack() {
            @Override
            public void run(Object result) {
                try {
                     AppResponse = (String) result;
                    response = ParseWeatherResponseXML
                            .parseMyTripXML(AppResponse);

                } catch (Exception e) {
                    Log.e("TAG Exception Occured",
                            "Exception is " + e.getMessage());
                }
            }
        });
        weatherReq.execute(url);
        return response;

    }

异步任务

public class WeatherUpdate extends AsyncTask<String, Void, String> {
    Context context;
    CallBack callBack;

    public WeatherUpdate(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected String doInBackground(String... arg0) {
        String responseString = "";
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            HttpGet get = new HttpGet(IweenTripDetails.url);
            client.getParams().setParameter("http.socket.timeout", 6000);
            client.getParams().setParameter("http.connection.timeout", 6000);
            HttpResponse responseGet = client.execute(get);
            HttpEntity resEntityGet = responseGet.getEntity();
            if (resEntityGet != null) {
                responseString = EntityUtils.toString(resEntityGet);
                Log.i("GET RESPONSE", responseString.trim());
            }
        } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
        }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
        return responseString.trim();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        callBack.run(result);

    }

}

【问题讨论】:

    标签: android android-asynctask android-inflate


    【解决方案1】:

    不是将 AsynChronous 任务保持在循环中,而是将循环保持在 AsynChronous 中。并使用onProgressUpdate 更新用户界面。

    更新示例代码

    public class Asyn extends AsyncTask<String, String, String> {
    
        @Override
        protected String doInBackground(String... params) {
            for (String location : params) {
                String tmp = getTemp(location);
                publishProgress(tmp);    /** Use Result **/
            }
            return null;
        }
    
        /**
         * Calculate Weather
         * 
         * @param location
         * @return
         */
        private String getTemp(String location) {
            return location;
        }
    
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            Log.e("Temo", values[0]);
        }
    
    }
    

    并传递您开始处理的位置数组

            Asyn m = new Asyn();
        String arrryaLocation = null; // your vales
        m.execute(arrryaLocation);
    

    【讨论】:

    • 这应该是评论。
    • @sameer 请详细说明我怎么能按照你的方式做到这一点
    • 看到我必须在循环中填充 XML 和 with 并且必须将我将从响应中收到的值放入。我必须如何做到这一点我没有得到那个
    • 使用 private String getTemp(String location) { return location; 中的每一行代码}
    • 你可以根据你的需求改变你的方法名,返回类型,参数
    【解决方案2】:

    Asynctask 中有 4 个方法,在 doInBackground() 方法中进行 HTTP 调用和解析数据,用于执行后台进程,inflate Layout inonPostExecute 方法用于执行 UI 操作。

    @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
    
                //Make your HTTP call and parse data
    
                return null;
        }
    

    和 UI 交互

    @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                // Inflate layout here
            }
    

    【讨论】:

    • 这应该是评论
    【解决方案3】:
      class MyAsyncTask extends AsyncTask<Void, Void, Void>    {
    
    
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                //parseing all details
            }
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // set up values for required params
            }
    
            @Override
            protected Void doInBackground(Void... arg0) {
                //make the web service call here
                return null;
            }   
        }   
    

    【讨论】:

    • 在 doInBackground 中运行一个循环
    • 我认为应该在答案中添加此评论:)
    【解决方案4】:

    这是从服务器获取数据并将其存储到数据库中的一个示例

    我在这里使用插入数据库中的数据总数更新 UI

      private class async extends AsyncTask<String, String, Boolean>
        {
                Context context;
                ProgressDialog pd;
                boolean flag ;
                Progress progress;
    
                async(Context mcontext)
                {
                    context = mcontext; 
                    pd = new ProgressDialog(activityContext);
                    progress = new Progress(this);
                } 
    
                @Override
                protected void onPreExecute() 
                {
                    pd.setTitle("Loading..");
    
                    pd.setMessage("Please Wait...!  " + NO + "  Record Inserted");
                    pd.setCancelable(false);
                    pd.show();
                    super.onPreExecute();
                }
    
                @Override
                protected Boolean doInBackground(String... params) 
                {
    
                    return flag = = getData(progress);
                }
    
                @Override
                protected void onProgressUpdate(String... values) 
                {
                    super.onProgressUpdate(values);
    
                    pd.setMessage("Please Wait..." + values[0].toString());
                }
    
                public class Progress 
                {
                    public async task;
    
                    public Progress(async task) 
                    {
                        this.task = task;
                    }
    
                    public void publish(String value) 
                    {
                        task.publishProgress(value);
                    }
                }
    
                @Override
                protected void onPostExecute(Boolean result) 
                {
                    super.onPostExecute(result);
    
                    if(pd.isShowing()) pd.dismiss();
                }
    }
    

    这里是 GetData 类:

    public boolean getData(Progress progress) 
            {
    
                while(true) // here you can use your loop 
                {
                    try
                    {
                        SoapObject soReturn ;
    
                        if(soReturn != null)
                        {
    
                    No = mNumber; // here i am getting total number is inserted in db
                        progress.publish(No); // No is published and sent it to progress update method.
    
    
                return true ;
            }
    

    调用它
    new async(context).execute();
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多