'안드로이드 xml 파싱'에 해당되는 글 1건

  1. 2012.03.13 안드로이드 트위터(twitter) 만들기 예제 따라하기
JAVA/Android2012.03.13 12:34

- 안드로이드에서 파싱 기술을 이용해서, 트위터 앱을 만들어 보자.
- XmlPullParser를 이용해, 트위터를 파싱하는 예제이다.

- Java 소스

public class Ex13_TwitterClientActivity extends Activity implements
  OnClickListener {
 static int ITEMCOUNT = 5;
 ArrayList<MyItem> mItems;
 CustomAdater mAdapter;
 String mName;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  mItems = new ArrayList<MyItem>();

  mAdapter = new CustomAdater(this, R.layout.item, mItems);

  ListView list = (ListView) this.findViewById(R.id.list);
  list.setAdapter(mAdapter);

  Button btn = (Button) this.findViewById(R.id.button1);
  btn.setOnClickListener(this);

 }

 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch (arg0.getId()) {
  case R.id.button1:
   EditText edit = (EditText) this.findViewById(R.id.editname);
   mName = edit.getText().toString();
   if (mName != null) {
    mItems.clear();
    String url = "http://twitter.com/statuses/user_timeline.xml?screen_name="
      + mName + "&count=" + ITEMCOUNT;

    // http://twitter.com/statuses/user_timeline.xml?screen_name=oisoo&count=5"
    String xml = downloadURL(url);
    parseXML(xml);
    mAdapter.notifyDataSetChanged();
   }

   break;

  }

 }

 void parseXML(String xml) {
  int itemtype = 0;
  //int itemtype2=0;
  String itemText = "";
  // MyItem temp = new MyItem();
  String tempicon = "", tempscreen = "", tempname = "", temptext = "", temptime = "";

  try {
   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
   XmlPullParser parser = factory.newPullParser();
   parser.setInput(new StringReader(xml));
   // 여기까지 의미있는부분을 짤라준다.
   int eventType = parser.getEventType();
   while (eventType != XmlPullParser.END_DOCUMENT) {
    switch (eventType) {
    case XmlPullParser.START_DOCUMENT:
     break;
    case XmlPullParser.END_DOCUMENT:
     break;
    case XmlPullParser.START_TAG:
     if (parser.getName().equals("profile_image_url"))itemtype = 1;
     if (parser.getName().equals("screen_name"))itemtype = 2;
     if (parser.getName().equals("name"))itemtype = 3;
     if (parser.getName().equals("text"))itemtype = 4;
     if (parser.getName().equals("created_at"))itemtype = 5;
     break;
    case XmlPullParser.END_TAG:
     if (parser.getName().equals("status")) {
      // mItems.add(new MyItem(temp));
      mItems.add(new MyItem(tempicon, tempscreen, tempname,
        temptext, temptime));
     }
     break;
    case XmlPullParser.TEXT:
     if (itemtype == 1) tempicon = parser.getText();
     if (itemtype == 2) tempscreen = parser.getText();
     if (itemtype == 3) tempname = parser.getText();
     if (itemtype == 4) temptext = parser.getText();
     if (itemtype == 5) temptime = parser.getText();
     
     itemtype = 0;
     break;
    }
    eventType = parser.next();
   }
  }
  catch (Exception e) {
   
  }
  // TextView text1 = (TextView)this.findViewById(R.id.tv1);
  // text1.setText(itemText);

 }

 String downloadURL(String addr) {
  String doc = "";
  try {
   URL url = new URL(addr);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   if (conn != null) {
    conn.setConnectTimeout(10000);
    conn.setUseCaches(false);
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 연결이
                   // 완성이됫다
     BufferedReader br = new BufferedReader(
       new InputStreamReader(conn.getInputStream()));
     for (;;) {
      String line = br.readLine();
      if (line == null)
       break;
      doc = doc + line + "\n";
     }
     br.close();
    }
     conn.disconnect();
   }
  } catch (Exception ex) {
   ;
  }

  return doc;

 }
}
----------------------------------------------------------------------------------------------------------------

public class CustomAdater extends BaseAdapter {
 Context context;
 int itemlayout;
 ArrayList<MyItem> arrayItems;
 LayoutInflater inflater;
 public CustomAdater(Context c, int sublayout, ArrayList<MyItem> list){
  this.context=c;
  this.itemlayout=sublayout;
  this.arrayItems=list;
  
  inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }
 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return arrayItems.size();
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return arrayItems.get(position);
 }

 @Override
 public long getItemId(int position) {
  // TODO Auto-generated method stub
  return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  // TODO Auto-generated method stub
  final int pos = position;
  
  if(convertView == null){
   convertView = inflater.inflate(itemlayout, parent,false);
  }
  
  ImageView img = (ImageView)convertView.findViewById(R.id.image1);
  //img.setImageResource(arrayItems.get(position).image);
  //img.setImageResource(R.drawable.icon);//초기화
  try{
   InputStream is = new URL(arrayItems.get(position).icon).openStream();
   Bitmap bit = BitmapFactory.decodeStream(is); // Factory 비트맵 다운로드
   img.setImageBitmap(bit);
   is.close();
  }
  catch(Exception e){
   img.setImageResource(R.drawable.icon);
  }
  
  TextView text1 = (TextView)convertView.findViewById(R.id.text1);
  text1.setText(arrayItems.get(position).scrren+"  "+arrayItems.get(position).name);
  
  TextView text2 = (TextView)convertView.findViewById(R.id.text2);
  text2.setText(arrayItems.get(position).text);
  
  TextView text3 = (TextView)convertView.findViewById(R.id.text3);
  text3.setText(arrayItems.get(position).time);
      
  return convertView;
 }

}
----------------------------------------------------------------------------------------------------------------public class MyItem {
 String icon, scrren, name, text, time;

 public MyItem(String icon, String scrren, String name, String text,
   String time) {
  this.icon = icon;
  this.scrren = scrren;
  this.name = name;
  this.text = text;
  this.time = time;
 }

 MyItem(MyItem obj) {
  this.icon = obj.icon;
  this.scrren = obj.scrren;
  this.name = obj.name;
  this.text = obj.text;
  this.time = obj.time;
 }

 MyItem() {

 }

}
----------------------------------------------------------------------------------------------------------------
-xml 소스
<!--main.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/editname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="load" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </ListView>
    </LinearLayout>

</LinearLayout>
----------------------------------------------------------------------------------------------------------------
<!--item.xml-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="0"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="5" />

        <TextView
            android:id="@+id/text3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>
----------------------------------------------------------------------------------------------------------------
-AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Ex13_TwitterClient.org"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Ex13_TwitterClientActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
     <uses-permission
    android:name="android.permission.INTERNET"/>
</manifest>
----------------------------------------------------------------------------------------------------------------- 실행 화면

신고
Posted by Namseungil