Android解析XML和JSON(部落格例子)

我叫阿狸貓發表於2014-02-23

MainActivity

public class MainActivity extends Activity {
    private ListView listLV;
	private List<Blog> blogs;

	private ListAdapter adapter = new BaseAdapter() {
		public View getView(int position, View convertView, ViewGroup parent) {//convertView表示:在上下拖動的時候,被移除螢幕外的那個條目
			View view = convertView==null?View.inflate(getApplicationContext(), R.layout.item, null):convertView;
			final ImageView headIV = (ImageView) view.findViewById(R.id.headIV);
			final ImageView contentIV = (ImageView) view.findViewById(R.id.contentIV);
			TextView titleTV = (TextView) view.findViewById(R.id.titleTV);
			TextView contentTV = (TextView) view.findViewById(R.id.contentTV);
			TextView fromTV = (TextView) view.findViewById(R.id.fromTV);
			final ImageService service = new ImageService(getApplicationContext());
			
			final Blog blog = blogs.get(position);
			
			Bitmap headBitMap = null;
			try {
				headBitMap = service.toBitMap(blog.getHeadImage());
			} catch (Exception e) {
				e.printStackTrace();
			}
			Bitmap contentBitMap = null;
			try {
				contentBitMap = service.toBitMap(blog.getContentImage());
			} catch (Exception e) {
				e.printStackTrace();
			}
			headIV.setImageBitmap(headBitMap);
			contentIV.setImageBitmap(contentBitMap);
			
			
			titleTV.setText(blog.getTitle());
			contentTV.setText(blog.getContent());
			fromTV.setText(blog.getFrom());
			
			
			return view;
		}
		public long getItemId(int position) {
			return position;
		}
		public Object getItem(int position) {
			return blogs.get(position);
		}
		public int getCount() {
			return blogs.size();
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listLV = (ListView) findViewById(R.id.listLV);
        final BlogService service = new BlogService();
		try {
			blogs = service.getBlogs("http://183.128.161.175:9090/15.Web/blogs.js");
			listLV.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}


BlogService:解析XML和解析JSON方法

public class BlogService {

	public List<Blog> getBlogs(String url) throws Exception {
		URL u = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		conn.setConnectTimeout(3000);
		
		InputStream is = conn.getInputStream();
		List<Blog> blogs = parseJSON(is);
		return blogs;
	}

	/**
	 * XML解析,返回Blog集合
	 * @param is
	 * @return
	 * @throws Exception
	 */
	private List<Blog> parseXML(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is,"UTF-8");
		List<Blog> blogs = new ArrayList<Blog>();
		Blog blog = null;
		for(int type=parser.getEventType();type!=XmlPullParser.END_DOCUMENT;type=parser.next()){
			if(type==XmlPullParser.START_TAG){
				if("blog".equals(parser.getName())){
					blog = new Blog();
					blogs.add(blog);
				}else if("portrait".equals(parser.getName())){
					blog.setHeadImage(parser.nextText());
				}else if("name".equals(parser.getName())){
					blog.setTitle(parser.nextText());
				}else if("content".equals(parser.getName())){
					blog.setContent(parser.nextText());
				}else if("pic".equals(parser.getName())){
					blog.setContentImage(parser.nextText());
				}else if("from".equals(parser.getName())){
					blog.setFrom(parser.nextText());
				}
			}
		}
		return blogs;
	}
	
	/**
	 * JSON解析,返回Blog集合
	 * @param is
	 * @return
	 * @throws Exception
	 */
	private List<Blog> parseJSON(InputStream is) throws Exception {
		byte[] buffer = Util.read(is);
		String json = new String(buffer);
		
		List<Blog> blogs = new ArrayList<Blog>();
		Blog blog = null;
		
		JSONArray array = new JSONArray(json);
		for(int i=0;i<array.length();i++){
			JSONObject obj = array.getJSONObject(i);
			blog = new Blog();
			blog.setHeadImage(obj.getString("portrait"));
			blog.setTitle(obj.getString("name"));
			blog.setContent(obj.getString("content"));
			blog.setContentImage(obj.getString("pic"));
			blog.setFrom(obj.getString("from"));
			blogs.add(blog);
		}
		return blogs;
	}
}


ImageService:將URL地址返回的二進位制資料以BitMap型別返回

/**
 * 接收一個URL地址引數,連線這個URL,將返回的資料流轉換成BitMap返回 
 */
public class ImageService {
	private Context context;
	public ImageService(Context context){
		this.context = context;
	}
	
	public Bitmap toBitMap(String headImage) throws Exception {
		URL url = new URL(headImage);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(3000);
		
		File cacheFile = new File(context.getCacheDir(),URLEncoder.encode(headImage));//獲取當前應用的快取檔案物件
		if(cacheFile.exists()){//如果存在快取檔案的話,就將快取檔案的最後修改時間設定到請求訊息中
			conn.setIfModifiedSince(cacheFile.lastModified());
		}
		Bitmap bitMap = null;
		
		int code = conn.getResponseCode();
		if(code==200){//如果響應碼為200就表示從網路上獲取圖片資料
			byte[] buffer = Util.read(conn.getInputStream());
			bitMap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
		}else if(code==304){//如果響應碼為304就表示使用快取圖片顯示
			bitMap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
		}
		return bitMap;
	}
}

Util

/**
 * 工具類:
 * 從輸入流中讀取資料以二進位制資料返回
 */
public class Util {
	public static byte[] read(InputStream is) throws IOException {
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		while((len=is.read(buffer))!=-1){
			bos.write(buffer, 0, len);
		}
		return bos.toByteArray();
	}
}

Domain

/**
 * 部落格物件 
 */
public class Blog {
	private String headImage;
	private String contentImage;
	private String title;
	private String content;
	private String from;

	@Override
	public String toString() {
		return "Blog [headImage=" + headImage + ", contentImage="
				+ contentImage + ", title=" + title + ", content=" + content
				+ ", from=" + from + "]";
	}

	public Blog(String headImage, String contentImage, String title,
			String content, String from) {
		this.headImage = headImage;
		this.contentImage = contentImage;
		this.title = title;
		this.content = content;
		this.from = from;
	}

	public Blog() {
		
	}

	public String getContentImage() {
		return contentImage;
	}

	public void setContentImage(String contentImage) {
		this.contentImage = contentImage;
	}

	public String getHeadImage() {
		return headImage;
	}

	public void setHeadImage(String headImage) {
		this.headImage = headImage;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}
}


效果如下:


相關文章