package kr.or.ddit.exoapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
// http://www.google.co.kr/ig/api?weather=seoul
//1.'위경도 -> 사람들이 사용하는 주소' 변환
//2.위에서 얻은 주소에서 도시이름 추출하여 해당 도시의 날씨 조사
// http://maps.googleapis.com/maps/api/geocode/json?latlng=36.324850,127.420040&sensor=false&language=en
public class ExOAPIActivity extends Activity {
TextView tv;
ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
ArrayList<Address> addrs = reverseGeoCoding(36.324850, 127.420040);
tv.setText(addrs.get(0).getLocality());
Weather wea = getWeather(addrs.get(0).getLocality());
tv.setText(tv.getText() + "\n" + wea.toString());
//
iv = (ImageView) findViewById(R.id.imageView1);
Bitmap bm = downloadBitmap("http://www.google.co.kr" + wea.iconUrl);
iv.setImageBitmap(bm);
}
Bitmap downloadBitmap(String url) {
Bitmap bmp = null;
InputStream is = null;
try{
is =new URL(url).openStream();
bmp = BitmapFactory.decodeStream(is);
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e ){
e.printStackTrace();
}finally{
try {
if (is != null) is.close();
}catch (IOException e){
e.printStackTrace();
}
}
new InputStream() {
@Override
public int read() throws IOException {
// TODO Auto-generated method stub
return 0;
}
};
BitmapFactory.decodeStream(is);
return bmp;
}
Weather getWeather(String city) {
Weather wea = new Weather();
try {
// new URL("http://www.google.co.kr/ig/api?weather=" + city);
// HttpURLConnection conn =(HttpURLConnection) url.openConnection();
// conn.setXXXX();
// conn.connect();
// InputStream is = conn.getInputStream();
InputStream is = new URL("http://www.google.co.kr/ig/api?weather="
+ city).openStream();
// 안드로이드의 xml 파서
// 1.Dom 파서 : 한번에 파싱을 완료하고 ㅡgetElent로 원하는 엘리먼트를 접근하여 사용
// 2.sax 파서: 어떤 엘리멘트들을 만나면 어떤 작업을 하도록 미리 정해 놓고 ,
// 파싱을 시작시키면 처음부터 끝까지 차싱을 진행하면서 처리
// 3. pull 파서 : 한 단계, 한 단계 파싱을 직접 진행 하면서,
// 어떤 엘리먼트을 만났는지 를 판단하고 원하는 작업을 수행
XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
XmlPullParser xpp = xppf.newPullParser();
xpp.setInput(is, "euc-kr");
boolean flag = true, currFlag = false;
while (flag) {
switch (xpp.next()) {
case XmlPullParser.START_DOCUMENT: // 문서의 시작을 만났을때
break;
case XmlPullParser.START_TAG: // 시작 태그를 만났을 때
if (xpp.getName().equals("current_conditions")) {
currFlag = true;
}
if (currFlag) {
if (xpp.getName().equals("condition")) {
wea.condition = xpp.getAttributeValue(0);
} else if (xpp.getName().equals("temp_f ")) {
wea.tempF = xpp.getAttributeValue(0);
} else if (xpp.getName().equals("temp_c")) {
wea.tempC = xpp.getAttributeValue(0);
} else if (xpp.getName().equals("humidity ")) {
wea.humidity = xpp.getAttributeValue(0);
} else if (xpp.getName().equals("icon")) {
wea.iconUrl = xpp.getAttributeValue(0);
} else if (xpp.getName().equals("wind_condition ")) {
wea.wind = xpp.getAttributeValue(0);
}
}
break;
case XmlPullParser.TEXT: // 시작 태그와 종료 태그 사이의 문자열을 만났을때
break;
case XmlPullParser.END_TAG: // 종료태그를 만났을때
if (xpp.getName().equals("current_conditions")) {
currFlag = false;
}
break;
case XmlPullParser.END_DOCUMENT: // 문서의 끝을 만났을 때
flag = false;
break;
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return wea;
}
class Weather {
String condition;
String tempC;
String tempF;
String humidity;
String wind;
String iconUrl;
@Override
public String toString() {
return "Weather [condition=" + condition + ", tempC=" + tempC
+ ", tempF=" + tempF + ", humidity=" + humidity + ", wind="
+ wind + ", iconUrl=" + iconUrl + "]";
}
}
ArrayList<Address> reverseGeoCoding(double lat, double lng) {
ArrayList<Address> addrList = new ArrayList<Address>();
BufferedReader br = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=false&language=en";
HttpGet req = new HttpGet(url);
HttpResponse rsp = client.execute(req);
InputStream is = rsp.getEntity().getContent();
StringBuffer result = new StringBuffer();
br = new BufferedReader(new InputStreamReader(is));
while (true) {
String str = br.readLine();
if (str == null)
break;
result.append(str);
}
tv.setText(result.toString());
JSONObject rootJObj = new JSONObject(result.toString());
JSONArray resultJArr = rootJObj.getJSONArray("results");
for (int i = 0; i < resultJArr.length(); i++) {
Address addr = new Address(Locale.getDefault());
JSONArray compJArr = resultJArr.getJSONObject(i).getJSONArray(
"address_components");
for (int j = 0; j < compJArr.length(); j++) {
JSONObject comJObj = compJArr.getJSONObject(j);
String type = comJObj.getJSONArray("types").getString(0);
if (type.equals("sublocality")) {
addr.setSubLocality(comJObj.getString("long_name"));
} else if (type.equals("locality")) {
addr.setLocality(comJObj.getString("long_name"));
} else if (type.equals("country")) {
addr.setCountryName(comJObj.getString("long_name"));
} else if (type.equals("postal_code")) {
addr.setPostalCode(comJObj.getString("long_name"));
}
}
addrList.add(addr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return addrList;
}
}























최근 덧글