前面一篇关于Volley的文章中,我们学习了如何利用ImageRequest去网络中加载图片,那么今天我们就来学习一下如何利用volley去网络中加载Json格式数据,并将其展示在一个ListView上。

1)数据源:

private static final String WEATHER_LINK = "http://www.weather.com.cn/data/sk/101280101.html";

这是由中国天气网提供的关于某个城市的天气预告的Json数据,大家直接点击链接进去 http://www.weather.com.cn/data/sk/101280101.html可以看到如下的数据:

{"weatherinfo":{"city":"广州","cityid":"101280101","temp":"12","WD":"东风","WS":"2级","SD":"95%","WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}

可以很清楚地看到这是一个Json格式的数据,其实JsonObject就是一个Map对象,所以这条链接提供的数据其实就是一个Weatherinfo的Map对象,它的属性值是Weatherinfo,然后其值是另外一个JsonObject对象,假设叫O,则这个O对象有很多属性,比如city,cityid,temp等,后面跟着的则是其对应的值。

那么我们如何在Android中利用Volley去获取这个数据呢?

2)Volley的应用

在这里,我们就用一个ListView简单地来展示其数据就好,先定义一个ListView,如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ListView        android:id="@+id/lvWeather"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </ListView></LinearLayout>

然后,我们要为这个ListView设定数据源,当然,我们先要去获取数据,那么接下来就是Volley的操作了。

跟前面ImageRequest的一样,我们首先也是要定义一个RequestQueue,如下:

private RequestQueue mQueue;

mQueue = Volley.newRequestQueue(this);
接下来,由于上面我们分析过,这个链接返回来的数据只是一个Object,并不是一个数组,所以在这里,我们需要使用的是JsonObjectRequest,而如果其它的链接返回来的是数组的结构,比如下面这样:

{"list":[{"id":"2775","cover":"http:\/\/app.itabcd.com\/\/public\/uploads\/news\/531d37fc5f460.jpg","title":"599 \u5143\uff0cNokia X \u4eac\u4e1c\u9884\u7ea6\u5f00\u542f",

在上面这种情况中,我们可以看到list是一个数组(其后面带有"[ ]"),那么我们就要使用JsonArrayRequest了。

接着看代码:

public void getWeatherInfo(){JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(WEATHER_LINK, null, new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject arg0) {list.clear();Iterator<String> it = arg0.keys();while(it.hasNext()){String key = it.next();JSONObject obj = null;try { obj = arg0.getJSONObject(key);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (obj != null) {Iterator<String> objIt = obj.keys();while (objIt.hasNext()) {String objKey = objIt.next();String objValue;try {objValue = obj.getString(objKey);HashMap<String, String> map = new HashMap<String, String>();map.put("title", objKey);map.put("content", objValue);Log.v(TAG, "title = " + objKey + " | content = " + objValue);list.add(map);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}Log.v(TAG, "list.size = " + list.size());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {}});mQueue.add(jsonObjectRequest);

在上面的代码中,我们利用的是JsonObjectRequest中的构造函数:

    /**     * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is     * <code>null</code>, <code>POST</code> otherwise.     *     * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)     */    public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,            ErrorListener errorListener) {        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,                listener, errorListener);    }
当我们将jsonRequest设置为null的时候,Volley会默认使用Get方式来发送我们的请求。

同样的,跟ImageRequest一样,我们需要实现两个回调函数,即两个Listener,一个是正常返回的数据,一个是错误返回的数据。

我们主要看的是Response.Listener里面的逻辑,在上面的代码中,可以看到,我们首先利用参数arg0的迭代器,获得第一个对象,此时,这个对象的key就是weatherinfo了,而其对应的值,其实还是一个JsonObject,所以,我们为了取得这个值里面的键值,我们需要再去遍历这个值中值,然后将其放到Map对象中,再将其放到list中。

其实逻辑很简单,是不?

然后我们利用SimpleAdapter来将数据展示出来,就好了,如下:

setContentView(R.layout.activity_json);lvWeather = (ListView)findViewById(R.id.lvWeather);mQueue = Volley.newRequestQueue(this);getWeatherInfo();//{"weatherinfo":{"city":"广州","cityid":"101280101","temp":"12","WD":"东风","WS":"2级","SD":"95%",//"WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, new String[] {"title","content"}, new int[] {android.R.id.text1, android.R.id.text2});lvWeather.setAdapter(simpleAdapter);

下面是效果图:


嗯,简单地应用就是这样了。源代码下载

关于如何利用Volley加载图片,大家可以参考:

Android中关于Volley的使用(一)加载图片

更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. 一句话锁定MySQL数据占用元凶
  3. Android中BaseFragment封装多状态视图显示
  4. Android中post请求传递json数据给服务端
  5. Android(安卓)添加数据到本地Excel表中
  6. android listview 实现从数据库读取已读功能,服务器通知增加,刷新l
  7. Android(安卓)结构组件之LiveData
  8. Android性能优化典范(四)
  9. android上层得到底层数据的回调机制

随机推荐

  1. Android常用组件之四大天王
  2. 由浅入深研究Android(1)--开篇•序
  3. error: Error parsing XML: unbound pref
  4. Ubuntu下安装VirtualBox和Android(安卓)
  5. Google Map Android v2开发: 安装运行Goo
  6. 关于 android 加载 res 图片 out of memo
  7. 【视频】 安卓渗透课程收集整理
  8. Gradle 构建 android 应用常见问题解决指
  9. Intent机制详解
  10. 快速上手Android数据库操作