설.현.아빠
[RssReader] XMLPullParser 이용하기. 본문
<?xml version="1.0" encoding="utf-8"?> <!--Androidmanifest.xml--> <manifest <uses-permission <?xml version="1.0" encoding="utf-8"?> <!--main.xml--> <LinearLayout <ListView <TextView <?xml version="1.0" encoding="utf-8"?> <!--row.xml--> <LinearLayout <TextView <?xml version="1.0" encoding="utf-8"?> <!--item_detail.xml--> <LinearLayout <TextView //SimpleRSSReaderActivity.java package lee.android.SimpleRSSReader; import java.util.ArrayList; import android.app.ListActivity; public class SimpleRSSReaderActivity extends ListActivity { requestWindowFeature(Window.FEATURE_NO_TITLE); // Create a List of Item objects for preservation and add an adapter. // Task Operation // RssListAdapter.java package lee.android.SimpleRSSReader; import java.util.List; import android.content.Context; public class RssListAdapter extends ArrayAdapter<Item> { public RssListAdapter(Context context, List<Item> objects) { // Create a view for each row if (convertView == null) { // ItemDetailActivity.java package lee.android.SimpleRSSReader; import android.app.Activity; public class ItemDetailActivity extends Activity { // Item.java package lee.android.SimpleRSSReader; public class Item { } // RssParserTask.java package lee.android.SimpleRSSReader; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import android.app.ProgressDialog; public class RssParserTask extends AsyncTask<String, Integer, RssListAdapter> { public RssParserTask(SimpleRSSReaderActivity activity, // Task 를 실행한 직후 제일 먼저 onPreExecute()가 호출된다. // Background 에서의 처리는 doInBackGround Method 가 담당한다. protected void onPostExecute(RssListAdapter result) { // XML Analysis } [출처] 간단한 RSS리더를 만들어보자 (안드로이드 개발자모임 [구글폰,HTC,삼성])
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" />
android:name="android.permission.INTERNET"
></uses-permission>
</manifest>
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</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" />
android:id="@+id/item_descr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="2"
android:ellipsize="end"
/>
</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"
/>
android:id="@+id/item_detail_descr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
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 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);
setContentView(R.layout.main);
mItems = new ArrayList<Item>();
mAdapter = new RssListAdapter(this, mItems);
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);
}
}
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ArrayAdapter;
private LayoutInflater mInflater;
private TextView mTitle;
private TextView mDescr;
super(context, 0, objects);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
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;
}
}
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
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);
}
}
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;
}
import java.io.InputStream;
import java.net.URL;
import org.xmlpull.v1.XmlPullParserException;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;
private SimpleRSSReaderActivity mActivity;
private RssListAdapter mAdapter;
private ProgressDialog mProgressDialog;
RssListAdapter adapter) {
mActivity = activity;
mAdapter = adapter;
}
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setMessage("Now Loading...");
mProgressDialog.show();
}
@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;
}
mProgressDialog.dismiss();
mActivity.setListAdapter(result);
}
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;
}
'안드로이드 > 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 |