1. 程式人生 > >android下載解析xml

android下載解析xml

android下載解析xml

public class MainActivity extends Activity {
        protected static final String PATH = "http://192.168.37.2:8081/news/news.xml";
        protected static final int TIME_OUT = 3000;
        private ListView lv_news;
        private Handler handler = new Handler(){
            @Override
public void handleMessage(Message msg){ switch (msg.what) { case RESULT_OK: List<Item> list = (List<Item>) msg.obj; lv_news.setAdapter(new MyAdapter(list,MainActivity.this)); break; case
RESULT_CANCELED: Log.d("tag", "RESULT_CANCELED"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv_news = (ListView) findViewById(R.id.lv_news); } public
void readNews(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(PATH); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(TIME_OUT); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode==200) { InputStream is = conn.getInputStream(); List<Item> items = parserXML(is); handler.obtainMessage(RESULT_OK, items).sendToTarget(); }else{ handler.obtainMessage(RESULT_CANCELED, "傳送失敗").sendToTarget(); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } protected List<Item> parserXML(InputStream is) throws Exception { XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "utf-8"); List<Item> list = null ; Item item = null ; int event =-1; while((event=parser.next())!=XmlPullParser.END_DOCUMENT){ String tagName = parser.getName(); if(event == XmlPullParser.START_TAG){ if("channel".equals(tagName)){ list = new ArrayList<Item>(); } else if ("item".equals(tagName)) { item = new Item(); }else if ("title".equals(tagName)) { item.tile = parser.nextText(); }else if ("description".equals(tagName)) { item.desc = parser.nextText(); }else if ("image".equals(tagName)) { item.image = parser.nextText(); }else if ("type".equals(tagName)) { item.type= parser.nextText(); }else if ("comment".equals(tagName)) { item.comment= parser.nextText(); } }else if (event==XmlPullParser.END_TAG) { if("item".equals(tagName)){ list.add(item); } } } return list; } }