Use of Volley in Android (2) Loading Json data

Source: Internet
Author: User
Tags radar

In the previous article about Volley, we learned how to use ImageRequest to load images on the network. Today we will learn how to use volley to load Json-format data on the network, and display it on a ListView.

1) Data source:

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

This is the weather forecast of a city of Json data provided by China weather network, you directly click the link into the http://www.weather.com.cn/data/sk/101280101.html can see the following data:

{"Weatherinfo": {"city": "Guangzhou", "cityid": "101280101", "temp": "12", "WD": "Dongfeng ", "WS": "Level 2", "SD": "95%", "WSE": "2", "time": "", "isRadar ": "1", "Radar": "JC_RADAR_AZ9200_JB "}}

We can clearly see that this is a Json data. In fact, JsonObject is a Map object, so the data provided by this link is actually a Map object of Weatherinfo, and its property value is Weatherinfo, then its value is another JsonObject object. Assume It is called O, then this O object has many attributes, such as city, cityid, temp, and so on, followed by its corresponding value.

So how can we use Volley in Android to obtain this data?

2) Volley applications

Here, we can simply use a ListView to display its data. First, define a ListView, as shown below:

<?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>

Then, we need to set the data source for this ListView. Of course, we need to obtain the data first, and then the Volley operation will be followed.

Like ImageRequest, we must first define a RequestQueue, as shown below:

private RequestQueue mQueue;

mQueue = Volley.newRequestQueue(this);
Next, as we have analyzed above, the data returned by this link is only an Object, not an array. So here, we need to use JsonObjectRequest, if other links return an array structure, such as the following:

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

In the above case, we can see that list is an array (followed by "[]"), then we will use JsonArrayRequest.

Next, let's look at the Code:

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

In the above Code, we use the constructor in 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);    }
When we set jsonRequest to null, Volley uses the Get method by default to send our request.

Similarly, like ImageRequest, we need to implement two callback functions, namely two Listener, one being normal returned data, and the other being error returned data.

We mainly look at Response. the logic in Listener. In the code above, we can see that we first use the arg0 iterator to obtain the first object. At this time, the key of this object is weatherinfo, the corresponding value is actually a JsonObject. Therefore, to obtain the key value in this value, we need to traverse the value and put it in the Map object, put it in the list.

In fact, the logic is very simple, right?

Then we can use SimpleAdapter to display the data as follows:

SetContentView (R. layout. activity_json); lvWeather = (ListView) findViewById (R. id. lvWeather); mQueue = Volley. newRequestQueue (this); getWeatherInfo (); // {"weatherinfo": {"city": "Guangzhou", "cityid": "101280101", "temp ": "12", "WD": "Dongfeng", "WS": "Level 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 );

Below is:


Well, it's just a simple application. Source code download

For details about how to use Volley to load images, refer:

Usage of Volley in Android (1) Loading Images

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.