Notice
Recent Posts
Recent Comments
Link
관리 메뉴

설.현.아빠

[RssReader] XMLPullParser 이용하기. 본문

안드로이드/Parser

[RssReader] XMLPullParser 이용하기.

설.현.아빠 2011. 2. 11. 11:02




 

<?xml version="1.0" encoding="utf-8"?>

 

<!--Androidmanifest.xml-->

 

<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="lee.android.SimpleRSSReader"
 android:versionCode="1"
 android:versionName="1.0"
>
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name"
 >
  <activity
   android:name=".SimpleRSSReaderActivity"
   android:label="@string/app_name"
  >
   <intent-filter>
    <action
     android:name="android.intent.action.MAIN" />
    <category
     android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
  <activity
   android:name=".ItemDetailActivity"
  ></activity>
 </application>
 <uses-sdk
  android:minSdkVersion="8" />

 <uses-permission
  android:name="android.permission.INTERNET"
 ></uses-permission>
</manifest>

 

 <?xml version="1.0" encoding="utf-8"?>

 

 <!--main.xml-->

 

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
>

 <ListView
  android:id="@android:id/list"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

 <TextView
  android:id="@android:id/empty"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
</LinearLayout>

 

 

<?xml version="1.0" encoding="utf-8"?>

 

<!--row.xml-->

 

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/item_container"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
>
 <TextView
  android:id="@+id/item_title"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textSize="18sp"
  android:lines="1" />

 <TextView
  android:id="@+id/item_descr"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:lines="2"
  android:ellipsize="end"
  />
</LinearLayout>

 

<?xml version="1.0" encoding="utf-8"?>

 

<!--item_detail.xml-->

 

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
>
 <TextView
  android:id="@+id/item_detail_title"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:background="@android:drawable/dark_header"
  />

 <TextView
  android:id="@+id/item_detail_descr"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
</LinearLayout>

 

//SimpleRSSReaderActivity.java

 

package lee.android.SimpleRSSReader;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ListView;

public class SimpleRSSReaderActivity extends ListActivity {
 public static final String RSS_FEED_URL = "http://itpro.nikkeibp.co.jp/rss/ITpro.rdf";
 private ArrayList<Item> mItems;
 private RssListAdapter mAdapter;
 public static final int MENU_ITEM_RELOAD = Menu.FIRST;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.main);

  // Create a List of Item objects for preservation and add an adapter.
  mItems = new ArrayList<Item>();
  mAdapter = new RssListAdapter(this, mItems);

  // Task Operation
  RssParserTask task = new RssParserTask(this, mAdapter);
  task.execute(RSS_FEED_URL); // RSS_FEED_URL은 doInBackground Method 의 Parameter 로 넘겨진다.
 }
 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  Item item = mItems.get(position);
  Intent intent = new Intent(this, ItemDetailActivity.class);
  intent.putExtra("TITLE", item.getTitle());
  intent.putExtra("DESCRIPTION", item.getDescription());
  startActivity(intent);
 }
 
 // Refresh Button add
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  boolean result = super.onCreateOptionsMenu(menu);
  menu.add(0, MENU_ITEM_RELOAD,0,"Refresh");
  return result;
 }
 
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch(item.getItemId()) {
  case MENU_ITEM_RELOAD:
   mItems = new ArrayList();
   mAdapter = new RssListAdapter(this,mItems);
   RssParserTask task = new RssParserTask(this, mAdapter);
   task.execute(RSS_FEED_URL);
   return true;
  }
  return super.onOptionsItemSelected(item);
 }
}

 

 

// RssListAdapter.java

 

package lee.android.SimpleRSSReader;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ArrayAdapter;

public class RssListAdapter extends ArrayAdapter<Item> {
 private LayoutInflater mInflater;
 private TextView mTitle;
 private TextView mDescr;

 public RssListAdapter(Context context, List<Item> objects) {
  super(context, 0, objects);
  mInflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 // Create a view for each row
 public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;

  if (convertView == null) {
   view = mInflater.inflate(R.layout.row, null);
  }
  Item item = this.getItem(position);
  if (item != null) {
   String title = item.getTitle().toString();
   mTitle = (TextView) view.findViewById(R.id.item_title);
   mTitle.setText(title);
   String descr = item.getDescription().toString();
   mDescr = (TextView) view.findViewById(R.id.item_descr);
   mDescr.setText(descr);
  }
  return view;
 }
}

 

// ItemDetailActivity.java

 

package lee.android.SimpleRSSReader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ItemDetailActivity extends Activity {
 private TextView mTitle;
 private TextView mDescr;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.item_detail);
  
  Intent intent = getIntent();
  
  String title = intent.getStringExtra("TITLE");
  mTitle = (TextView)findViewById(R.id.item_detail_title);
  mTitle.setText(title);
  String descr = intent.getStringExtra("DESCRIPTION");
  mDescr = (TextView)findViewById(R.id.item_detail_descr);
  mDescr.setText(descr);
 }
}

 

 

// Item.java

 

package lee.android.SimpleRSSReader;

public class Item {
 private CharSequence mTitle; // Article Title
 private CharSequence mDescription; // Acticle Body
 public Item() {
  mTitle="";
  mDescription="";
 }
 
 public CharSequence getDescription() {
  return mDescription;
 }
 
 public void setDescription(CharSequence description) {
  mDescription = description;
 }
 public CharSequence getTitle() {
  return mTitle;
 }
 public void setTitle(CharSequence title) {
  mTitle = title;
 }

}

 

 

// RssParserTask.java

 

package lee.android.SimpleRSSReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;

public class RssParserTask extends AsyncTask<String, Integer, RssListAdapter> {
 private SimpleRSSReaderActivity mActivity;
 private RssListAdapter mAdapter;
 private ProgressDialog mProgressDialog;

 public RssParserTask(SimpleRSSReaderActivity activity,
   RssListAdapter adapter) {
  mActivity = activity;
  mAdapter = adapter;
 }

 // Task 를 실행한 직후 제일 먼저 onPreExecute()가 호출된다.
 @Override
 protected void onPreExecute() {
  mProgressDialog = new ProgressDialog(mActivity);
  mProgressDialog.setMessage("Now Loading...");
  mProgressDialog.show();
 }

 // Background 에서의 처리는 doInBackGround Method 가 담당한다.
 @Override
 protected RssListAdapter doInBackground(String... arg0) {
  RssListAdapter result = null;
  try {
   // HTTP경유로 접속하고, InputStream을 취득
   URL url = new URL(arg0[0]);
   InputStream is = url.openConnection().getInputStream();
   result = parseXml(is);
  } catch (Exception e) {
   e.printStackTrace();
  }
  // 여기에서 넘겨주는 값은 onPostExecute Method 의 Parameter 로 넘겨진다.
  return result;
 }

 protected void onPostExecute(RssListAdapter result) {
  mProgressDialog.dismiss();
  mActivity.setListAdapter(result);
 }

 // XML Analysis
 public RssListAdapter parseXml(InputStream is) throws IOException,
   XmlPullParserException {
  XmlPullParser parser = Xml.newPullParser();
  /*
   * <item rdf:about="
http://itpro.nikkeibp.co.jp/article/NEWS/20101108/353908/"> 
   * <title>「婚活??」のAndroidアプリ、インデックスHDがFeliCa搭載端末向けに無料提供(ニュ?ス)</title>
   * <link>http://itpro.nikkeibp.co.jp/article/NEWS/20101108/353908/</link>
   * <description> インデックス?ホ?ルディングスは2010年11月8日、FeliCa搭載端末同士をタッチすることで相性診?やメ?ルアドレスの送信などが手
   * ?に行えるAndroidアプリ「Touch Friends」を?表した。NTTドコモが同日?表した「LYNX 3D
   * SH-03C」などのFeliCa搭載端末で動作する。</description>
   * <dc:date>2010-11-08T16:58:00+09:00</dc:date> </item>
   */
  try {
   parser.setInput(is, null);
   int eventType = parser.getEventType();
   Item currentItem = null;
   while (eventType != XmlPullParser.END_DOCUMENT) {
    String tag = null;
    switch (eventType) {
    case XmlPullParser.START_TAG: // "<>를 만났을 때
     tag = parser.getName();
     if (tag.equals("item")) {
      currentItem = new Item();
     } else if (currentItem != null) {
      if (tag.equals("title")) {
       currentItem.setTitle(parser.nextText());
      } else if (tag.equals("description")) {
       currentItem.setDescription(parser.nextText());
      }
     }
     break;
    case XmlPullParser.END_TAG: // "</>"를 만났을 때
     tag = parser.getName();
     if(tag.equals("item")) {
      mAdapter.add(currentItem);
     }
     break;
    }
    eventType = parser.next();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return mAdapter;
 }

}

 

[출처] 간단한 RSS리더를 만들어보자 (안드로이드 개발자모임 [구글폰,HTC,삼성])


'안드로이드 > Parser' 카테고리의 다른 글

Data Feed / RSS 예제  (0) 2011.02.11
[학습자료] 안드로이드에서 JSON 처리 방법  (3) 2011.02.11
Jericho API  (0) 2011.02.11
[HTML Parsing] 해당 페이지의 모든 문자 출력  (0) 2011.02.11
Jericho HTML Parser  (0) 2011.02.11
Comments