日期:2014-05-16 浏览次数:20489 次
前面一篇关于Volley的文章中,我们学习了如何利用ImageRequest去网络中加载图片,那么今天我们就来学习一下如何利用volley去网络中加载Json格式数据,并将其展示在一个ListView上。
1)数据源:
private static final String WEATHER_LINK = "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"}}
那么我们如何在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>跟前面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>() {
@Override
public 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 block
e.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);