Android中关于Volley的使用(二)加载Json数据

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

1)数据源:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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  可以看到如下的数据:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. {"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,如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <ListView  
  8.         android:id="@+id/lvWeather"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" >  
  11.     </ListView>  
  12.   
  13. </LinearLayout>  

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

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private RequestQueue mQueue;  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. mQueue = Volley.newRequestQueue(this);  
接下来,由于上面我们分析过,这个链接返回来的数据只是一个Object,并不是一个数组,所以在这里,我们需要使用的是JsonObjectRequest,而如果其它的链接返回来的是数组的结构,比如下面这样:

[plain]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. {"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了。

接着看代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void getWeatherInfo(){  
  2.     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(WEATHER_LINK, null,   
  3.             new Response.Listener<JSONObject>() {  
  4.                 @Override  
  5.                 public void onResponse(JSONObject arg0) {  
  6.                     list.clear();  
  7.                     Iterator<String> it = arg0.keys();  
  8.                     while(it.hasNext()){  
  9.                         String key = it.next();  
  10.                         JSONObject obj = null;  
  11.                         try {  
  12.                              obj = arg0.getJSONObject(key);  
  13.                         } catch (JSONException e) {  
  14.                             // TODO Auto-generated catch block  
  15.                             e.printStackTrace();  
  16.                         }  
  17.                         if (obj != null) {  
  18.                             Iterator<String> objIt = obj.keys();  
  19.                             while (objIt.hasNext()) {  
  20.                                 String objKey = objIt.next();  
  21.                                 String objValue;  
  22.                                 try {  
  23.                                 objValue = obj.getString(objKey);  
  24.                                 HashMap<String, String> map = new HashMap<String, String>();  
  25.                                 map.put("title", objKey);  
  26.                                 map.put("content", objValue);  
  27.                                 Log.v(TAG, "title = " + objKey + " | content = " + objValue);  
  28.                                 list.add(map);  
  29.                                 } catch (JSONException e) {  
  30.                                     // TODO Auto-generated catch block  
  31.                                     e.printStackTrace();  
  32.                                 }  
  33.                             }  
  34.                         }  
  35.                     }  
  36.                     Log.v(TAG, "list.size = " + list.size());  
  37.                 }             
  38.             }, new Response.ErrorListener() {  
  39.                 @Override  
  40.                 public void onErrorResponse(VolleyError arg0) {  
  41.                 }  
  42.             });  
  43.     mQueue.add(jsonObjectRequest);  

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is 
  3.  * <code>null</code>, <code>POST</code> otherwise. 
  4.  * 
  5.  * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener) 
  6.  */  
  7. public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,  
  8.         ErrorListener errorListener) {  
  9.     this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,  
  10.             listener, errorListener);  
  11. }  
当我们将jsonRequest设置为null的时候,Volley会默认使用Get方式来发送我们的请求。

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

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

其实逻辑很简单,是不?

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. setContentView(R.layout.activity_json);  
  2.   
  3. lvWeather = (ListView)findViewById(R.id.lvWeather);  
  4.   
  5. mQueue = Volley.newRequestQueue(this);  
  6. getWeatherInfo();  
  7. //{"weatherinfo":{"city":"广州","cityid":"101280101","temp":"12","WD":"东风","WS":"2级","SD":"95%",  
  8. //"WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}  
  9. SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,   
  10.         android.R.layout.simple_list_item_2, new String[] {"title","content"},   
  11.         new int[] {android.R.id.text1, android.R.id.text2});              
  12.   
  13. lvWeather.setAdapter(simpleAdapter);  

下面是效果图:


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是加载json文件并绘制图形的代码示例: 1. 首先,在Android Studio创建一个新项目,并在app/build.gradle文件添加以下依赖项: implementation 'com.android.volley:volley:1.1.1' implementation 'com.github.mikephil:charting:3.1.' 2. 在MainActivity.java文件添加以下代码: import android.graphics.Color; import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private RequestQueue mQueue; private BarChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mChart = findViewById(R.id.chart); mQueue = Volley.newRequestQueue(this); jsonParse(); } private void jsonParse() { String url = "https://api.myjson.com/bins/1e7j9u"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("data"); ArrayList<BarEntry> entries = new ArrayList<>(); for (int i = ; i < jsonArray.length(); i++) { JSONObject data = jsonArray.getJSONObject(i); float value = (float) data.getDouble("value"); entries.add(new BarEntry(i, value)); } BarDataSet dataSet = new BarDataSet(entries, "Data"); dataSet.setColor(Color.BLUE); BarData barData = new BarData(dataSet); mChart.setData(barData); mChart.invalidate(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "onErrorResponse: ", error); } }); mQueue.add(request); } } 3. 在activity_main.xml文件添加以下代码: <?xml version="1." encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.github.mikephil.charting.charts.BarChart android:id="@+id/chart" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> 这段代码将从指定的URL加载JSON数据,解析它,并将其用于绘制柱状图。您可以将URL替换为您自己的JSON数据源,并根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值