Reputation: 21
This is regarding Weatherforecastapp using Volley..
How do we replace the following code with Volley?
Since we are new to android we are finding it difficult to implement 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() + ")");
}
}
Upvotes: 2
Views: 1505
Reputation: 3022
The good news is that Volley is much easier to use than AsyncTask! :)
Volley has a a few types of requests that it can make. For your implementation, it looks like you are retrieving JSON. Volley has special request for JSONObject and JSONArray, so you would use whichever makes sense for you.
Here is a basic outline of how you would replace your code with Volley. Note that the onResponse is the callback (like onPostExecute in AsyncTask).
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);
}
}
Here is a great talk on Volley, to learn more about it: https://developers.google.com/events/io/sessions/325304728
Upvotes: 1