Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 解析網絡json數據並展示到ListView上

解析網絡json數據並展示到ListView上

編輯:關於Android編程

網易新聞看起來很簡潔,左邊是一張圖片,右邊是一些文字信息,這樣的排版是十分常見的,給人的感覺就是簡潔明了,下面通過解析網絡json數據並展示到ListView上,來實現同樣的效果,效果圖如下:

\

 

1.數據來源於網上json數據的解析,網址為http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo=1&pageSize=20&v=4.0.0(可能過段時間就失效了),如果想了解json解析或者獲取json數據接口,參照:http://blog.csdn.net/ljw124213/article/details/52313758。json的格式如下(這裡只解析title,image和pubDate三個字段):

\

 

2.先寫出解析此json數據的實體類:

 

package com.example.listview;

import java.util.ArrayList;

public class CarBean {
	
	public ArrayListdata;
	
	public static class Car{
		public String title;
		public String pubDate;
		public String image;
	}
}

3.解析json數據的工具類:

 

 

package com.example.listview;

import com.google.gson.Gson;

public class JsonUtils {
	public static CarBean parseJson(String jsonString){
		Gson gson = new Gson();
		CarBean cb = gson.fromJson(jsonString, CarBean.class);
		return cb;
	}
}
注意:使用Gson解析的話,必須先下載Gson的jar包,放到工程的libs目錄下,下載地址:http://download.csdn.net/detail/ljw124213/9612607

 

4.從網絡上下載數據的工具類:

 

package com.example.listview;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtils {

	public static byte[] getNetData(String urlString){
		try {
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("GET");
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			
			byte[] result = null;
			if (conn.getResponseCode() == 200) {
				InputStream is = conn.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len=is.read(buffer))!=-1){
					baos.write(buffer, 0, len);
				}
				result = baos.toByteArray();
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

5.下載android-smart-image-view開源框架,把其src下的部分復制到自己工程的src下面,下載地址(帶有使用詳解):http://download.csdn.net/detail/ljw124213/9630820

 

6.准備工作完成之後,下面開始實現具體功能,創建一個異步任務類,來下載網絡數據:

 

package com.example.listview;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.example.listview.CarBean.Car;

public class DownAsynctask extends AsyncTask{

	ArrayListdata;
	MyAdapter adapter;
	Context context;
	
	public DownAsynctask(ArrayList data, MyAdapter adapter, Context context) {
		super();
		this.data = data;
		this.adapter = adapter;
		this.context = context;
	}

	/*
	 * 當主線程中調用executeOnExecutor方法或execute方法時,會調用此方法
	 */
	@Override
	protected byte[] doInBackground(String... params) {
		//下載網絡數據
		return NetUtils.getNetData(params[0]);
	}

	/*
	 * doInBackground方法執行之後會執行此方法,並把結果傳過來
	 */
	@Override
	protected void onPostExecute(byte[] result) {
		super.onPostExecute(result);
		if (result != null) {
			//把從網絡上獲取的byte類型的數據轉換為String字符串
			String jsonString = new String(result);
			//用json解析工具來解析該字符串數據
			CarBean cb = JsonUtils.parseJson(jsonString);
			//取出data數據,並保存到集合中
			data.addAll(cb.data);
			//刷新數據
			adapter.notifyDataSetChanged();
		}else {
			Toast.makeText(context, "網絡異常", Toast.LENGTH_SHORT).show();
		}
	}
}


 

 


 

 

7.創建一個數據適配器,用來加載數據:

package com.example.listview;

import java.util.ArrayList;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.listview.CarBean.Car;
import com.loopj.android.image.SmartImageView;

public class MyAdapter extends BaseAdapter{

	ArrayList data;
	Context context;
	
	public MyAdapter(ArrayList data, Context context) {
		super();
		this.data = data;
		this.context = context;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		//初始化holder對象
		ViewHold holder;
		if(convertView == null){
			//把條目布局轉化為view對象
			convertView = View.inflate(context, R.layout.item, null);
			//初始化holder對象,並初始化holder中的控件
			holder = new ViewHold();
			holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
			holder.tv_date = (TextView) convertView.findViewById(R.id.tv_date);
			holder.iv = (SmartImageView) convertView.findViewById(R.id.iv);
			//給當前view做個標記,並把數據存到該tag中
			convertView.setTag(holder);
			
		}else {
			 //如果當前view存在,則直接從中取出其保存的控件及數據
			holder = (ViewHold) convertView.getTag();
		}
		//通過position獲取當前item的car數據,從car數據中取出title、pubDate和image
		Car car = data.get(position);
		holder.tv_title.setText(car.title);
		holder.tv_date.setText(car.pubDate);
		
		//使用SmartImageView的setImageUrl方法下載圖片
		holder.iv.setImageUrl(car.image);
		
		return convertView;
	}

	/*
	 * 用來存放item布局中控件的holder類
	 */
	class ViewHold{
		SmartImageView iv; //顯示圖片的控件,注意是SmartImageView
		TextView tv_title; //顯示標題的控件
		TextView tv_date;  //顯示日期的控件
	}
}

 

 

 


8.在MainActivity中進行數據的匯總:

 

 

package com.example.listview;

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.example.listview.CarBean.Car;

public class MainActivity extends Activity {

	private ListView lv;
	private ArrayList data;
	private MyAdapter adapter;
	private boolean flag = false;
	private int pageNo = 1;
	private ExecutorService es;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化listview控件
		lv = (ListView) findViewById(R.id.lv);
		//存放json解析的數據的集合
		data = new ArrayList();
		//自定義適配器
		adapter = new MyAdapter(data,this);
		
		//給listview設置一個底部view(必須在設置數據之前)
		View footView = View.inflate(this, R.layout.foot, null);
		lv.addFooterView(footView);
		
		//給listview設置適配器
		lv.setAdapter(adapter);
		
		//使用線程池來實現異步任務的多線程下載
		es = Executors.newFixedThreadPool(10);
		new DownAsynctask(data,adapter,this).executeOnExecutor(es, "http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo="+pageNo+"&pageSize=20&v=4.0.0");
		
		/*
		 * 對listview設置滾動監聽事件,實現分頁加載數據
		 */
		lv.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				//如果停止了滑動且滑動到了結尾,則更新數據,加載下一頁
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && flag == true) {
					pageNo += 1;
					new DownAsynctask(data,adapter,MainActivity.this).executeOnExecutor(es, "http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo="+pageNo+"&pageSize=20&v=4.0.0");
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				//判斷是否滑動到了結尾
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					flag = true;
				}else {
					flag = false;
				}
			}
		});
	}
}

 

 

 


9.ListView對應的布局文件activity_main.xml:

 

 



    

 

 

10.ListView對應的item的布局文件item.xml:

 



    
    
    
    
        
        
    

 

11.ListView尾布局對應的布局文件footer.xml:

 

 



    
	
	



 

 

提示:此數據接口可能很快就不能用來,如果需要測試的話,可以把原數據放到tomcat服務器中進行測試,下面是完整數據:

 

{
    "data": [
        {
            "articleType": "n",
            "count": 29,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/8/14733163729178590_600.jpg",
            "id": "8562073",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/08/g_8562073_1473339813478_240x160.jpg",
            "mtime": 1473351348000,
            "pubDate": "2016-09-09",
            "title": "新福特翼虎購車手冊 家用中配足夠實用",
            "ups": 26,
            "url": "http://www.pcauto.com.cn/teach/856/8562073.html"
        },
        {
            "articleType": "n",
            "count": 37,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1608/31/8655654_toutu_thumb.jpg",
            "id": "8655654",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8655654_1472800030976_240x160.jpg",
            "mtime": 1473351337000,
            "pubDate": "2016-09-09",
            "title": "年輕人第一台車 10萬左右精品車型推薦",
            "ups": 130,
            "url": "http://www.pcauto.com.cn/teach/865/8655654.html"
        },
        {
            "articleType": "n",
            "count": 35,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/06/8719572_toutu_thumb.jpg",
            "id": "8719572",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/06/g_8719572_1473152785181_240x160.jpg",
            "mtime": 1473264982000,
            "pubDate": "2016-09-08",
            "title": "豪門不“壕” 4款入門豪華SUV僅售23萬起",
            "ups": 143,
            "url": "http://www.pcauto.com.cn/teach/871/8719572.html"
        },
        {
            "articleType": "n",
            "count": 40,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/1/14727375445822660_600.jpg",
            "id": "8705572",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/07/g_8705572_1473242245557_240x160.jpg",
            "mtime": 1473264969000,
            "pubDate": "2016-09-08",
            "title": "明銳對比英朗 當歐洲紳士遇上美國大漢",
            "ups": 52,
            "url": "http://www.pcauto.com.cn/teach/870/8705572.html"
        },
        {
            "articleType": "n",
            "count": 68,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/6/14731526553913750_600.jpg",
            "id": "8719262",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/06/g_8719262_1473151845818_240x160.jpg",
            "mtime": 1473153591000,
            "pubDate": "2016-09-06",
            "title": "新晉英倫長軸距座駕 捷豹XFL實拍解析",
            "ups": 299,
            "url": "http://www.pcauto.com.cn/teach/871/8719262.html"
        },
        {
            "articleType": "n",
            "count": 100,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/07/8695292_999_thumb.jpg",
            "id": "8695292",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/01/g_8695292_1472695974218_240x160.jpg",
            "mtime": 1473137438000,
            "pubDate": "2016-09-06",
            "title": "15萬元搞定 四款獨立後懸掛合資SUV推薦",
            "ups": 117,
            "url": "http://www.pcauto.com.cn/teach/869/8695292.html"
        },
        {
            "articleType": "n",
            "count": 84,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/06/8718677_xin1000_thumb.jpg",
            "id": "8718677",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/05/g_8718677_1473061488223_240x160.jpg",
            "mtime": 1473092132000,
            "pubDate": "2016-09-06",
            "title": "8萬元選靠譜SUV 4款新推自主車型推薦",
            "ups": 91,
            "url": "http://www.pcauto.com.cn/teach/871/8718677.html"
        },
        {
            "articleType": "n",
            "count": 96,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20168/29/14724733055558460_600.jpg",
            "id": "8683971",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8683971_1472803720871_240x160.jpg",
            "mtime": 1473005791000,
            "pubDate": "2016-09-05",
            "title": "凱美瑞對比雅閣 誰才是日系中級車霸主",
            "ups": 65,
            "url": "http://www.pcauto.com.cn/teach/868/8683971.html"
        },
        {
            "articleType": "n",
            "count": 136,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/04/8716791_00_thumb.jpg",
            "id": "8716791",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/04/g_8716791_1473002216143_240x160.jpg",
            "mtime": 1473005746000,
            "pubDate": "2016-09-05",
            "title": "精華都在這裡 成都車展最值得關注的SUV",
            "ups": 390,
            "url": "http://www.pcauto.com.cn/teach/871/8716791.html"
        },
        {
            "articleType": "n",
            "count": 26,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/4/14729794978954170_600.jpg",
            "id": "8716391",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/04/g_8716391_1472979896686_240x160.jpg",
            "mtime": 1472980188000,
            "pubDate": "2016-09-04",
            "title": "2016成都車展:靜態評測奔馳新一代威霆",
            "ups": 312,
            "url": "http://www.pcauto.com.cn/teach/871/8716391.html"
        },
        {
            "articleType": "n",
            "count": 32,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/01/8700555_8207206_03_thumb.jpg",
            "id": "8700555",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/01/g_8700555_1472716638381_240x160.jpg",
            "mtime": 1472919329000,
            "pubDate": "2016-09-04",
            "title": "入門性價比爆炸 新款致炫購車手冊",
            "ups": 91,
            "url": "http://www.pcauto.com.cn/teach/870/8700555.html"
        },
        {
            "articleType": "n",
            "count": 70,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728310541595730_600.jpg",
            "id": "8712133",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8712133_1472831164431_240x160.jpg",
            "mtime": 1472832200000,
            "pubDate": "2016-09-03",
            "title": "2016成都車展:靜態評測北京現代勝達",
            "ups": 468,
            "url": "http://www.pcauto.com.cn/teach/871/8712133.html"
        },
        {
            "articleType": "n",
            "count": 41,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/02/8710078_1000_thumb.jpg",
            "id": "8710078",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710078_1472810381352_240x160.jpg",
            "mtime": 1472817162000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態評測新款瑪莎拉蒂總裁",
            "ups": 299,
            "url": "http://www.pcauto.com.cn/teach/871/8710078.html"
        },
        {
            "articleType": "n",
            "count": 62,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728116986128820_600.jpg",
            "id": "8711094",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8711094_1472812405190_240x160.jpg",
            "mtime": 1472812618000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態評測大眾新桑塔納",
            "ups": 1053,
            "url": "http://www.pcauto.com.cn/teach/871/8711094.html"
        },
        {
            "articleType": "n",
            "count": 28,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728073809221840_600.jpg",
            "id": "8710334",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710334_1472807999865_240x160.jpg",
            "mtime": 1472808197000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態體驗北京現代悅納",
            "ups": 247,
            "url": "http://www.pcauto.com.cn/teach/871/8710334.html"
        },
        {
            "articleType": "n",
            "count": 31,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728054816668520_600.jpg",
            "id": "8710116",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710116_1472805803455_240x160.jpg",
            "mtime": 1472806069000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態評測東南DX3",
            "ups": 247,
            "url": "http://www.pcauto.com.cn/teach/871/8710116.html"
        },
        {
            "articleType": "n",
            "count": 60,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728006933643890_600.jpg",
            "id": "8709146",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8709146_1472801055169_240x160.jpg",
            "mtime": 1472801551000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態評測寶馬X1混動版",
            "ups": 806,
            "url": "http://www.pcauto.com.cn/teach/870/8709146.html"
        },
        {
            "articleType": "n",
            "count": 87,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14727918621883140_600.jpg",
            "id": "8708181",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8708181_1472793809972_240x160.jpg",
            "mtime": 1472794520000,
            "pubDate": "2016-09-02",
            "title": "2016成都車展:靜態評測東風本田競瑞",
            "ups": 533,
            "url": "http://www.pcauto.com.cn/teach/870/8708181.html"
        },
        {
            "articleType": "n",
            "count": 34,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/02/8704693_toutu_thumb.jpg",
            "id": "8704693",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8704693_1472787714022_240x160.jpg",
            "mtime": 1472793542000,
            "pubDate": "2016-09-02",
            "title": "沖擊市場有力競爭者 新科沃茲購車手冊",
            "ups": 117,
            "url": "http://www.pcauto.com.cn/teach/870/8704693.html"
        },
        {
            "articleType": "n",
            "count": 111,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14727803654960920_600.jpg",
            "id": "8706132",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8706132_1472781925547_240x160.jpg",
            "mtime": 1472781940000,
            "pubDate": "2016-09-02",
            "title": "7座對標漢蘭達 斯柯達KODIAQ實拍解析",
            "ups": 104,
            "url": "http://www.pcauto.com.cn/teach/870/8706132.html"
        }
    ],
    "pageNo": 1,
    "pageSize": 20,
    "total": 200
}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved