簡體   English   中英

如何用排球替換AsyncTask

[英]how to replace AsyncTask with Volley

這是關於使用Volley的Weatherforecastapp。

我們如何用Volley替換以下代碼?

由於我們是android的新手,因此發現很難實現Volley。

private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

        @Override
        protected Weather doInBackground(String... params) {
            Weather weather = new Weather();
            String data = ( (new WeatherHttpClient()).getWeatherData(params[0], params[1]));

            try {
                weather = JSONWeatherParser.getWeather(data);
                System.out.println("Weather ["+weather+"]");
                // Let's retrieve the icon
                weather.iconData = ( (new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));

            } catch (JSONException e) {             
                e.printStackTrace();
            }
            return weather;

    }


    @Override
    protected void onPostExecute(Weather weather) {         
            super.onPostExecute(weather);

            if (weather.iconData != null && weather.iconData.length > 0) {
                Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length); 
                imgView.setImageBitmap(img);
            }


            cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
            temp.setText("" + Math.round((weather.temperature.getTemp() - 275.15)));
            condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");


        }
  }

好消息是Volley比AsyncTask更容易使用! :)

排球可以提出幾種類型的請求。 對於您的實現,您似乎正在檢索JSON。 Volley對JSONObject和JSONArray有特殊要求,因此您將使用對您有意義的任何一種。

這是如何用Volley替換代碼的基本概述。 請注意,onResponse是回調(例如AsyncTask中的onPostExecute)。

private class WeatherTask{    
    public void getWeatherData() {

        // Create a single queue
        RequestQueue queue = Volley.newRequestQueue(this);

        // Define your request
        JsonObjectRequest getRequest = new JsonObjectRequest(url,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JsonObject jsonObject) {

                      // Parse JSON here

                    }
                }
            }
            , new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    // Show Error message
                    Log.e("Error Response: ", volleyError.toString());
                }
            }
         );

        // add it to the Request Queue
        queue.add(getRequest);

    }
}

這是有關Volley的精彩演講,以了解更多信息: https : //developers.google.com/events/io/sessions/325304728

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM