package com.gyarmy.xmlweather; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.xmlpull.v1.XmlPullParser; import com.gyarmy.xmlweather.domain.Product; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.util.Xml; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { protected static final int SUCCESS = 0; protected static final int ERROR = 1; protected static final int NETWORK_ERROR = 2; private EditText city_code; private TextView city_name; private TextView city_wendu; private TextView city_fengxiang; private String path; private Handler mHandler=new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case SUCCESS: Product p = (Product)msg.obj; city_name.setText(p.getCity()); city_wendu.setText(p.getWendu()); city_fengxiang.setText(p.getFengxiang()); break; case ERROR: break; case NETWORK_ERROR: break; default: break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); city_code = (EditText)findViewById(R.id.city_code); city_name = (TextView)findViewById(R.id.city_name); city_wendu = (TextView)findViewById(R.id.city_wendu); city_fengxiang = (TextView)findViewById(R.id.city_fengxiang); } public void getResult(View v){ String code_data = city_code.getText().toString().trim(); path = "http://wthrcdn.etouch.cn/WeatherApi?citykey="+code_data; new Thread(){ public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(2000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); if(200 == code){ InputStream in = conn.getInputStream(); XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, "UTF-8"); int eventType = parser.getEventType(); Product p = new Product(); while(eventType != parser.END_DOCUMENT) { if("city".equals(parser.getName())) { p.setCity(parser.nextText()); }else if("wendu".equals(parser.getName())){ p.setWendu(parser.nextText()); }else if("fengxiang".equals(parser.getName())){ p.setFengxiang(parser.nextText()); } eventType = parser.next(); } Message msg = Message.obtain(); msg.obj = p; msg.what = SUCCESS; mHandler.sendMessage(msg); }else{ Message msg= Message.obtain(); msg.what = ERROR; mHandler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block Message msg= Message.obtain(); msg.what = NETWORK_ERROR; mHandler.sendMessage(msg); e.printStackTrace(); } }; }.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
0则评论给“网络编程中的xml解析案例”