note

Xml 가져오기 (날씨) 본문

Android/기본

Xml 가져오기 (날씨)

투한 2012. 1. 19. 11:52


실행 화면



인터넷 권한 있어야 합니다
(manifest.xml -> permission -> INTERNET
 


  main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webkit"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />


WeatherDemo
package kr.android.weather;

import android.app.Activity;
import android.os.Bundle;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

public class WeatherDemo extends Activity {
	// 기상청 날씨 정보
	private static final String WEATHER_URL =
			"http://www.kma.go.kr/XML/weather/sfc_web_map.xml";
	private WebView browser;
	private List forecasts = new ArrayList();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		browser = (WebView) findViewById(R.id.webkit);
		updateForecast();
	}

	private void updateForecast() {
		buildForecastsByXmlPullParser(getStreamFromUrl());
		String page = generatePage();

		browser.loadDataWithBaseURL(null, page, "text/html", "UTF-8", null);
	}

	private InputStream getStreamFromUrl() {
		InputStream input = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(WEATHER_URL);
			// 응답을 받을 객체
			HttpResponse response = (HttpResponse) client.execute(getMethod);
			// 응답 수신 처리
			HttpEntity entity = response.getEntity();
			BufferedHttpEntity buf = new BufferedHttpEntity(entity);
			input = buf.getContent();
		} catch (Exception e) {
			Log.e("WeatherDemo", "Exception fetching data", e);
			Toast.makeText(this, "요청 실패 : e.toString()", 4000).show();
		}
		return input;
	}

	private void buildForecastsByXmlPullParser(InputStream input) {
		String desc = null;
		String temp = null;
		String locale = null;
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();

			// 파서에 스트림 연결(null = default = "UTF-8")
			parser.setInput(input, null);

			while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlPullParser.START_TAG) {
					//equal은 객체비교 equals는 문자열비교
					if (parser.getName().equals("local")) {

						// 날씨 처리
						desc = parser.getAttributeValue(2);
						// 온도 처리
						temp = parser.getAttributeValue(3);
					}
				} else if (parser.getEventType() == XmlPullParser.TEXT) {
					// 지역 정보 처리
					locale = parser.getText();
				} else if (parser.getEventType() == XmlPullParser.END_TAG) {
					forecasts.add(new Forecast(locale, desc, temp));
				}
				// XML의 파서 커서를 다음 태그로 이동시킴
				parser.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String generatePage() {
		StringBuilder bufResult = new StringBuilder(
				"");

		bufResult.append(""
				+ "");

		for (Forecast forecast : forecasts) {
			bufResult.append("");
		}

		bufResult.append("
지역날씨온도
"); bufResult.append(forecast.locale); bufResult.append(" "); bufResult.append(forecast.desc); bufResult.append(" "); bufResult.append(forecast.temp); bufResult.append("
"); return (bufResult.toString()); } class Forecast { String locale; String desc; String temp; public Forecast(String locale, String desc, String temp) { this.locale = locale; this.desc = desc; this.temp = temp; } } }