java - 如何用 Volley 替换 AsyncTask

标签 java android json

这是关于使用 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 更容易使用! :)

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);

    }
}

这里有一个关于 Volley 的精彩演讲,要了解更多信息:https://developers.google.com/events/io/sessions/325304728

关于java - 如何用 Volley 替换 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20965186/

相关文章:

用于移动浏览器的 Android AVD 模拟器开发工具?

java - Android中解析JSON的问题

java - 使用 Play Java 从 Firebase 接收 Json

java - 您需要在单元测试中使用 Theme.AppCompat 主题 -->

java - Eclipse 插件无法从类文件夹中找到类

android - 在 android 中使用 rest api 和解析数据、jackson 或 groovy 的最佳方法是什么?

c# - 以 JSON 形式返回 Entity Framework 结果

java - IE 使用 SSL 连接阻止文件下载 - CacheControl 问题

java - 将 System.out.print 转换为 JOptionPane?

java - 如何定义 CardView 的边距