你的位置:首页 > 操作系统

[操作系统][android] 天气app布局练习(四)


主要练习一下获取网络数据和解析

MainActivity.java

package com.example.weatherreport;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.widget.GridView;import android.widget.SimpleAdapter;import android.widget.TextView;import com.example.weatherreport.contants.ApiContants;import com.example.weatherreport.domain.Weather;import com.example.weatherreport.net.HttpListener;import com.example.weatherreport.net.HttpUtil;public class MainActivity extends Activity {  private GridView gv_airs;  private TextView tv_city;  private TextView tv_number;  private TextView tv_rain;  private TextView tv_cloth;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    gv_airs = (GridView) findViewById(R.id.gv_airs);    tv_city=(TextView) findViewById(R.id.tv_city);    tv_number=(TextView) findViewById(R.id.tv_number);    tv_rain=(TextView) findViewById(R.id.tv_rain);    tv_cloth=(TextView) findViewById(R.id.tv_cloth);    setViewData();    makeGridView();  }  /**   * 设置界面数据   */  private void setViewData() {    String city = null;    try {      city = URLEncoder.encode("北京", "gb2312");    } catch (UnsupportedEncodingException e) {      e.printStackTrace();    }    HttpUtil.get(ApiContants.WEATHER_URL+"?city="+city+"&password=DJOYnieT8234jlsK&day=0", new HttpListener() {      @Override      public void onSuccess(String result) {        Weather weather=(Weather) HttpUtil.public void onError(String result) {        System.out.println(result);      }    });  }  protected void setViewWeather(Weather weather) {    tv_city.setText(weather.getCity());    tv_number.setText(weather.getHot());    tv_rain.setText(weather.getRain());    tv_cloth.setText(weather.getCloth());    System.out.println(weather.toString());  }  /**   * 组装GridView   */  private void makeGridView() {    List<Map<String, String>> data = new ArrayList<>();    Map<String, String> item = null;    item = new HashMap<>();    item.put("title", "83");    item.put("desc", "湿度(%)");    data.add(item);    item = new HashMap<>();    item.put("title", "11.3");    item.put("desc", "可见度(km)");    data.add(item);    item = new HashMap<>();    item.put("title", "2级");    item.put("desc", "东南风");    data.add(item);    item = new HashMap<>();    item.put("title", "最弱");    item.put("desc", "紫外线");    data.add(item);    item = new HashMap<>();    item.put("title", "1005.5");    item.put("desc", "气压(mb)");    data.add(item);    item = new HashMap<>();    item.put("title", "22.4");    item.put("desc", "体感");    data.add(item);    SimpleAdapter adapter = new SimpleAdapter(this, data,        R.layout.main_grid_item, new String[] { "title", "desc" },        new int[] { R.id.tv_title, R.id.tv_desc });    gv_airs.setAdapter(adapter);  }}

 

HttpUtil.java

package com.example.weatherreport.net;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.StringReader;import java.net.HttpURLConnection;import java.net.URL;import org.import android.os.Handler;import android.os.Message;import android.util.import com.example.weatherreport.domain.Weather;public class HttpUtil {  public static final int SUCCESS = 1;  public static final int ERROR = 2;  /**   * 获取get数据   *   * @param apiUrl   */  public static void get(final String apiUrl, final HttpListener listener) {    final Handler handler = new HttpHandler(listener);    new Thread(new Runnable() {      @Override      public void run() {        Message msg = new Message();        try {          URL url = new URL(apiUrl);          HttpURLConnection conn = (HttpURLConnection) url              .openConnection();          conn.setRequestMethod("GET");          conn.setConnectTimeout(5000);          int code = conn.getResponseCode();          if (code == 200) {            InputStream is = conn.getInputStream();            String result = readInputStream(is);            msg.what = SUCCESS;            msg.obj = result;            handler.sendMessage(msg);          } else {            listener.onError(String.valueOf(code));          }        } catch (Exception e) {          e.printStackTrace();          msg.what = ERROR;          msg.obj = "网络异常";          handler.sendMessage(msg);        }      }    }).start();  }  /**   * 读取输入流   *   * @param is   * @return   */  public static String readInputStream(InputStream is) {    ByteArrayOutputStream baos = new ByteArrayOutputStream();    int len = 0;    byte[] buffer = new byte[1024];    try {      while ((len = is.read(buffer)) != -1) {        baos.write(buffer, 0, len);      }      is.close();      byte[] res = baos.toByteArray();      return new String(res);    } catch (Exception e) {      e.printStackTrace();    }    return null;  }  /**   * 解析@return   */  public static Object = new Weather();    try {      = new StringReader(int event = pullParser.getEventType();      while (event != switch (event) {        case = pullParser.getName();          if (tagName.equals("Weather") || tagName.equals("Profiles")) {          } else {            String tagValue = pullParser.nextText();            System.out.println(tagName + ":" + tagValue);            if (tagName.equals("status1")) {              weather.setRain(tagValue);            }            if (tagName.equals("tgd1")) {              weather.setHot(tagValue);            }            if (tagName.equals("chy_l")) {              weather.setCloth(tagValue);            }            if (tagName.equals("city")) {              weather.setCity(tagValue);            }          }          break;        case default:          break;        }        event = pullParser.next();      }    } catch (Exception e) {      e.printStackTrace();    }    return weather;  }}/** * * 位于主线程的Handler * @author taoshihan * */class HttpHandler extends Handler {  private HttpListener listener;  public HttpHandler(HttpListener listener) {    this.listener=listener;  }  @Override  public void handleMessage(Message msg) {    int flag=msg.what;    String res=(String)msg.obj;    if (flag==HttpUtil.SUCCESS) {      listener.onSuccess(res);    }else{      listener.onError(res);    }  }}

HttpListener.java

package com.example.weatherreport.net;public interface HttpListener {  public void onSuccess(String result);  public void onError(String result);}