Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

天氣 App 布局練習(四):網絡數據獲取與 XML 解析

編輯:關於 Android 程式設計

本節重點是把網絡請求與 XML 解析串起來,讓界面上的天氣數據真正來自服務端,而不是寫死的常量。

MainActivity.java

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;
        try {
            city = URLEncoder.encode("北京", "gb2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        HttpUtil.get(ApiContants.WEATHER_URL + "?city=" + city
                + "&password=DJOYnieT8234jlsK&day=0", new HttpListener() {
            @Override
            public void onSuccess(String result) {
                Weather weather = (Weather) HttpUtil.xml2object(result);
                setViewWeather(weather);
            }

            @Override
            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());
    }

    /** 組裝 GridView */
    private void makeGridView() {
        List<Map<String, String>> data = new ArrayList<>();
        data.add(item("83", "濕度(%)"));
        data.add(item("11.3", "可見度(km)"));
        data.add(item("2級", "東南風"));
        data.add(item("最弱", "紫外線"));
        data.add(item("1005.5", "氣壓(mb)"));
        data.add(item("22.4", "體感"));

        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);
    }

    private Map<String, String> item(String title, String desc) {
        Map<String, String> map = new HashMap<>();
        map.put("title", title);
        map.put("desc", desc);
        return map;
    }
}

HttpUtil.java

網絡工具類承擔三件事:發起 GET 請求、讀取輸入流、把 XML 轉成對象。線程切換則借助 Handler 完成,子線程負責請求,主線程負責回調界面。

public class HttpUtil {

    public static final int SUCCESS = 1;
    public static final int ERROR = 2;

    /** 獲取 GET 數據 */
    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);
                    if (conn.getResponseCode() == 200) {
                        String result = readInputStream(conn.getInputStream());
                        msg.what = SUCCESS;
                        msg.obj = result;
                    } else {
                        listener.onError(String.valueOf(conn.getResponseCode()));
                        return;
                    }
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = ERROR;
                    msg.obj = "網絡異常";
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    /** 讀取輸入流 */
    public static String readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            return new String(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 解析 XML */
    public static Object xml2object(String xmlString) {
        Weather weather = new Weather();
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(xmlString));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:
                        String tagName = parser.getName();
                        if (!tagName.equals("Weather") && !tagName.equals("Profiles")) {
                            String value = parser.nextText();
                            if (tagName.equals("status1")) {
                                weather.setRain(value);
                            } else if (tagName.equals("tgd1")) {
                                weather.setHot(value);
                            } else if (tagName.equals("chy_l")) {
                                weather.setCloth(value);
                            } else if (tagName.equals("city")) {
                                weather.setCity(value);
                            }
                        }
                        break;
                    default:
                        break;
                }
                event = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return weather;
    }
}

/** 位於主線程的 Handler */
class HttpHandler extends Handler {
    private final HttpListener listener;

    public HttpHandler(HttpListener listener) {
        this.listener = listener;
    }

    @Override
    public void handleMessage(Message msg) {
        String res = (String) msg.obj;
        if (msg.what == HttpUtil.SUCCESS) {
            listener.onSuccess(res);
        } else {
            listener.onError(res);
        }
    }
}

HttpListener.java

回調接口保持簡單,只區分成功與失敗兩種結果:

public interface HttpListener {
    void onSuccess(String result);
    void onError(String result);
}

整條鏈路可以概括為:Activity 拼接請求地址並提交,HttpUtil 在子線程完成請求與解析,結果通過 Handler 回到主線程,最後由 setViewWeather 更新界面。相比直接寫死數據,這種分層方式後續替換數據源時只需改動工具類即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved