2014-01-07 55 views
2

这是关于使用Volley的Weatherforecastapp ..如何用Volley替换AsyncTask

如何用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() + ")"); 


     } 
    } 
+0

http://java.dzone.com/articles/android-%E2%80%93-volley-library – Armand

回答

1

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

Volley有一些类型的请求,它可以使。对于您的实现,它看起来像您正在检索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); 

    } 
} 

这里是凌空精彩演讲,以了解更多有关它:https://developers.google.com/events/io/sessions/325304728