Android解析XML和JSON(部落格例子)
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();
}
}
}
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;
}
}
效果如下:
相關文章
- 解析XML和JSON內容的一點技巧XMLJSON
- Android中解析XMLAndroidXML
- 10分鐘掌握XML、JSON及其解析XMLJSON
- json listView 資料請求解析小例子JSONView
- 依賴注入的很好的一個部落格例子依賴注入
- XML和JSON的介紹XMLJSON
- android 開源和一些部落格總結Android
- Android之XML檔案解析AndroidXML
- android複雜json解析AndroidJSON
- 優秀Android開發者的部落格Android
- JSON和XML:不可同日而語JSONXML
- Android系列--DOM、SAX、Pull解析XMLAndroidXML
- Android中XML的解析--使用PULLAndroidXML
- android 解析xml 到 AttributeSet物件AndroidXML物件
- [android]AndroidManifest.xml解析AndroidXML
- 基於github和hexo搭建部落格 本地hexo部落格搭建GithubHexo
- 自己實現JSON、XML的解析 沒那麼難JSONXML
- android使用Gson來解析jsonAndroidJSON
- android解析HashMap格式的jsonAndroidHashMapJSON
- Android系列---JSON資料解析AndroidJSON
- hexo搭建部落格以及域名解析分析Hexo
- Android學習部落格資源收藏Android
- 還在比較 JSON 和 XML?Stop!JSONXML
- XML與JSONXMLJSON
- Android 中 XML 資料解析詳解AndroidXML
- android JSON解析資料-解析天氣預報AndroidJSON
- Android手動建立和解析JsonAndroidJSON
- nomasp 部落格導讀:Lisp/Emacs、Algorithm、AndroidLispMacGoAndroid
- WebApi介面 - 響應輸出xml和jsonWebAPIXMLJSON
- 部落格園的部落格中插入公式公式
- 部落格園部落格記錄備份
- android下解析.plist配置檔案的xml解析器AndroidXML
- Xml解析XML
- 使用 Nginx 和 Gunicorn 部署 Django 部落格NginxDjango
- 我對部落格的理解和看法
- RecyclerView綜合案例庫和系列部落格View
- 使用github和hexo搭建部落格GithubHexo
- 再談JSON/XMLJSONXML