獲取伺服器json資料並解析顯示listview上
阿新 • • 發佈:2019-02-03
通過伺服器返回的json資料並解析顯示到listview控制元件上:
執行圖:
伺服器返回json格式:
{ "activity": [ { "name": "天王蓋地虎", "startTime": "2017-03-02 00:00" }, { "name": "寶塔鎮河妖", "startTime": "2017-03-02 00:00" }, { "name": "鋤禾日當午", "startTime": "2017-03-02 00:00" }, { "name": "汗滴禾下土", "startTime": "2017-03-02 00:00" }, { "name": "誰知盤中餐", "startTime": "2017-03-02 00:00" }, { "name": "粒粒皆辛苦", "startTime": "2017-03-02 00:00" }, { "name": "套路深鋼磨成針", "startTime": "2017-03-02 00:00" }, { "name": "這個世界都是假的", "startTime": "2017-03-02 00:00" }, { "name": "套路深鋼磨成針", "startTime": "2017-03-02 00:00" }, { "name": "套路深鋼磨成針", "startTime": "2017-03-02 00:00" } ], "description": "查詢成功", "flag": "success" }
1、activity_main佈局中新增listview控制元件
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
新增好listview控制元件後,
建立listview的item佈局起名為:listview_item
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="80dp" android:gravity="center" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試活動" /> <TextView android:layout_marginTop="20dp" android:id="@+id/shijian" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試時間" /> </LinearLayout> </RelativeLayout>
這裡面就是2個文字用來顯示json中的資料
2、MainActivity程式碼編輯
佈局完成後來看一下activity中程式碼:
下載完成後解壓檔案,把2個架包匯入libs中(2個架包都需要匯入)
public JSONObject object; public ListView lv; public ArrayList<Map<String, Object>> list=new ArrayList<Map<String,Object>>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { list.clear(); lv=(ListView) findViewById(R.id.lv); new Thread(new Runnable() { @Override public void run() { OkHttpClient okHttpClient=new OkHttpClient(); //伺服器返回的地址 Request request=new Request.Builder() .url("http://10.0.2.2/date.json").build(); try { Response response=okHttpClient.newCall(request).execute(); //獲取到資料 String date=response.body().string(); //把資料傳入解析josn資料方法 jsonJX(date); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start();; } private void jsonJX(String date) { //判斷資料是空 if(date!=null){ try { //將字串轉換成jsonObject物件 JSONObject jsonObject = new JSONObject(date); //獲取返回資料中flag的值 String resultCode = jsonObject.getString("flag"); //如果返回的值是success則正確 if (resultCode.equals("success")) { //獲取到json資料中裡的activity陣列內容 JSONArray resultJsonArray = jsonObject.getJSONArray("activity"); //遍歷 for(int i=0;i<resultJsonArray.length();i++){ object=resultJsonArray.getJSONObject(i); Map<String, Object> map=new HashMap<String, Object>(); try { //獲取到json資料中的activity數組裡的內容name String name = object.getString("name"); //獲取到json資料中的activity數組裡的內容startTime String shijian=object.getString("startTime"); //存入map map.put("name", name); map.put("shijian", shijian); //ArrayList集合 list.add(map); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Message message = new Message(); message.what = 1; handler.sendMessage(message); } } catch (JSONException e) { e.printStackTrace(); } } } //Handler執行在主執行緒中(UI執行緒中), 它與子執行緒可以通過Message物件來傳遞資料 @SuppressLint("HandlerLeak") public Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: Mybaseadapter list_item=new Mybaseadapter(); lv.setAdapter(list_item); break; } } }; //listview的介面卡 public class Mybaseadapter extends BaseAdapter { @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = getLayoutInflater().inflate(R.layout.listview_item, null); viewHolder.textView = (TextView) convertView.findViewById(R.id.tv); viewHolder.shijian = (TextView) convertView.findViewById(R.id.shijian); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.textView.setText(list.get(position).get("name").toString()); viewHolder.shijian.setText(list.get(position).get("shijian").toString()); return convertView; } } final static class ViewHolder { TextView textView; TextView shijian; }
注意:這裡如果不開啟handler將會報錯:android.view.ViewRootImpl$CalledFromWrongThreadException錯誤。
最後1步 既然訪問網路就必須新增訪問網路許可權: <uses-permission android:name="android.permission.INTERNET" />
好了到這裡就能正常顯示並解析出來了
相關文章: