2015-6-10 XML解析之Pull解析方式
今天是来成都实训的第三天,一如既往的坐在电脑前,敲代码,解决BUG,做代码的搬运工,标准的CV战士,不过,每天都还是有些收获,一边写着自己的日记本,一边听老师讲些基础的知识,虽然分心了,不过收获还是算满意了。 今天学会了用Pull方式解析XML,直接上案例,做一个简单的RSS阅读器。 一、新建Android工程,工程结构图如下: package com.scitc.rssreader;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import com.example.rssreader.R;
import com.scitc.rssreader.adapter.RssAdapter;
import com.scitc.rssreader.entity.RssItem;
import com.scitc.rssreader.utils.DataUtil;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView lv_app;
private final int RESPONSE_CODE = 1;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RESPONSE_CODE:
List<RssItem> apps=(List<RssItem>) msg.obj;
RssAdapter adapter=new RssAdapter(getApplicationContext(),R.layout.list_item,apps);
lv_app.setAdapter(adapter);
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(DataUtil.URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
// 判断响应是否成功
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
List<RssItem> apps= getRssItems(response);
Message message=new Message();
message.what=RESPONSE_CODE;
message.obj=apps;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/** * 用pull方式解析XML * * @param response */
private List<RssItem> getRssItems(String is) {
List<RssItem> list = null;
RssItem item = null;
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(is));
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<RssItem>();
break;
case XmlPullParser.START_TAG:
if ("item".equals(parser.getName())) {
item = new RssItem();
}
if (item != null) {
if ("title".equals(parser.getName())) {
item.setTitle(parser.nextText());
} else if ("link".equals(parser.getName())) {
item.setLink(parser.nextText());
} else if ("description".equals(parser.getName())) {
item.setDescription(parser.nextText());
} else if ("pubDate".equals(parser.getName())) {
item.setPubDate(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
if ("item".equals(parser.getName())) {
list.add(item);
item = null;
}
break;
}
type = parser.next();
}
return list;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private void initView() {
lv_app = (ListView) findViewById(R.id.rss_list);
}
}
RssAdapter.java package com.scitc.rssreader.adapter;
import java.util.List;
import com.example.rssreader.R;
import com.scitc.rssreader.entity.RssItem;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class RssAdapter extends ArrayAdapter<RssItem> {
private int resourceId;
/** * * @param context 上下文对象 * @param textViewResourceId 布局文件 * @param objects 集合对象 */
public RssAdapter(Context context,int textViewResourceId,List<RssItem> objects) {
super(context,textViewResourceId,objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position,View convertView,ViewGroup parent) {
RssItem rssItem = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId,null);
} else {
view = convertView;
}
TextView tvIdText = (TextView) view.findViewById(R.id.tv_title);
tvIdText.setText(rssItem.getTitle()+"");
TextView tvNameText = (TextView) view.findViewById(R.id.tv_pubDate);
tvNameText.setText(rssItem.getPubDate());
return view;
}
}
RssItem.java package com.scitc.rssreader.entity;
public class RssItem {
private String title;
private String pubDate;
private String description;
private String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
DataUtil.java package com.scitc.rssreader.utils;
public class DataUtil {
public final static String URL="http://www.people.com.cn/rss/politics.xml";
}
layout目录下的布局文件 <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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.scitc.rssreader.MainActivity" >
<ListView
android:id="@+id/rss_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
list_item.xml <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" >
<TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="marquee"/>
<TextView android:id="@+id/tv_pubDate" android:layout_width="match_parent" android:layout_height="wrap_content"/>
</LinearLayout>
这就是所有的代码部分了,最后添加访问网络权限 <uses-permission android:name="android.permission.INTERNET"/>
运行结果图: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |