<activity android:name=".RSSMainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
2. RSSMainActivity:
1) 用ListView显示RSS Reader获取的数据结果
定义ListView的list layout 和 item layout
activity_postlist.xml
<?xml version="1.0" encoding="utf-8"?> <!-- activity_postlist.xml --> <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=".RSSMainActivity" > <ListView android:id="@+id/postListView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
postitem.xml: 显示RSS的title和pubDate
<?xml version="1.0" encoding="utf-8"?> <!-- postitem.xml --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="5dp" android:paddingBottom="5dp" > <ImageView android:id="@+id/postThumb" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/ic_launcher" android:scaleType="centerCrop" android:layout_marginRight="5dp"/> <TextView android:id="@+id/postTitleLabel" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@id/postThumb" android:layout_toRightOf="@id/postThumb" android:maxLines="2" android:text="This is a good Post, I hope it will have 2 lines. Please give me 2 lines" android:textIsSelectable="false" android:textSize="14sp" android:ellipsize="end"/> <TextView android:id="@+id/postDateLabel" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignBottom="@id/postThumb" android:layout_toRightOf="@id/postThumb" android:maxLines="1" android:text="April 12, 2013" android:textSize="10sp" /> </RelativeLayout>
RSSMainActivity.java中,添加listview。
public class RSSMainActivity extends Activity { private ArrayList<PostData> listData = new ArrayList<PostData>(); private PostItemAdapter itemAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_postlist); ListView listView = (ListView) this.findViewById(R.id.postListView); itemAdapter = new PostItemAdapter(this,R.layout.postitem, listData); listView.setAdapter(itemAdapter); } }
定义RSSFeed的Model
public class PostData { public String postThumbUrl; public String postTitle; public String postDate; }
2) 自定义Adapter, 实现listView.setAdapter的方法
public class PostItemAdapter extends ArrayAdapter<PostData> { private Activity myContext; private ArrayList<PostData> datas; static class ViewHolder{ TextView postTitleView; TextView postDateView; ImageView postThumbView; } public PostItemAdapter(Context context, int textViewResourceId, ArrayList<PostData> objects){ super(context, textViewResourceId, objects); myContext = (Activity) context; datas = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView==null){ LayoutInflater inflater = myContext.getLayoutInflater(); convertView = inflater.inflate(R.layout.postitem, null); viewHolder = new ViewHolder(); viewHolder.postThumbView = (ImageView) convertView.findViewById(R.id.postThumb); viewHolder.postTitleView = (TextView) convertView.findViewById(R.id.postTitleLabel); viewHolder.postDateView = (TextView) convertView.findViewById(R.id.postDateLabel); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } if(datas.get(position).postThumbUrl == null){ viewHolder.postThumbView.setImageResource(R.drawable.ic_launcher); } viewHolder.postTitleView.setText(datas.get(position).postTitle); viewHolder.postDateView.setText(datas.get(position).postDate); return convertView; } }
3) 使用AsyncTask从后台获取数据
在RSSMainActivity中定义AsyncTask, 使用HttpURLConnection获取数据,并解析显示在 list中
private enum RSSXMLTag{ TITLE, DATE, LINK, CONTENT, GUID, IGNORETAG; } private class RSSDataController extends AsyncTask<String, Integer, ArrayList<PostData>>{ private RSSXMLTag currentTag; @Override protected void onPostExecute(ArrayList<PostData> result) { for(int i=0;i<result.size();i++){ listData.add(result.get(i)); } itemAdapter.notifyDataSetChanged(); } @Override protected ArrayList<PostData> doInBackground(String... params) { String urlStr = params[0]; InputStream is = null; ArrayList<PostData> postDataList = new ArrayList<PostData>(); try{ URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10*1000); connection.setConnectTimeout(10*1000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); int response = connection.getResponseCode(); Log.d("debug", "the response is:" + response); is = connection.getInputStream(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(is,null); int eventType = xpp.getEventType(); PostData pdData = null; SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); while (eventType!=XmlPullParser.END_DOCUMENT){ if(eventType == XmlPullParser.START_DOCUMENT){ }else if(eventType == XmlPullParser.START_TAG){ if(xpp.getName().equals("item")){ pdData = new PostData(); currentTag = RSSXMLTag.IGNORETAG; }else if(xpp.getName().equals("title")){ currentTag = RSSXMLTag.TITLE; }else if(xpp.getName().equals("link")){ currentTag = RSSXMLTag.LINK; }else if(xpp.getName().equals("pubDate")){ currentTag = RSSXMLTag.DATE; } }else if(eventType == XmlPullParser.END_TAG){ if(xpp.getName().equals("item")){ Date postDate = dateFormat.parse(pdData.postDate); pdData.postDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(postDate); postDataList.add(pdData); }else{ currentTag = RSSXMLTag.IGNORETAG; } }else if(eventType == XmlPullParser.TEXT){ String content = xpp.getText(); content = content.trim(); Log.d("debug", content); if(pdData!=null){ switch (currentTag){ case TITLE: if(content.length()!=0){ if(pdData.postTitle !=null){ pdData.postTitle += content; }else{ pdData.postTitle = content; } } break; case LINK: if(content.length()!=0){ if(pdData.postThumbUrl!=null){ pdData.postThumbUrl += content; }else{ pdData.postThumbUrl = content; } } break; case DATE: if(content.length()!=0){ if(pdData.postDate !=null){ pdData.postDate += content; }else{ pdData.postDate = content; } } break; default: break; } } } eventType = xpp.next(); } }catch(MalformedURLException e){ Log.e("malformedURL error", e.getLocalizedMessage()); }catch(IOException e){ Log.e("IO error", e.getLocalizedMessage()); }catch(XmlPullParserException e){ Log.e("XmlPullParser error", e.getLocalizedMessage()); } catch (ParseException e) { Log.e("Parse error", e.getLocalizedMessage()); } return postDataList; } }
在RSSMainActivity中启用onStart方法,在该方法中运行后台AsyncTask的服务
@Override protected void onStart() { super.onStart(); RSSDataController task = new RSSDataController(); String rssUrl = "http://10.4.251.146/igrp/rssfeed.rss"; String[] params = new String[]{rssUrl}; task.execute(params); }