가상청 사이트에가서 RSS 주소를 알아오자..
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout>mainfast.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gusfree.weatherparse" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".WeatherParseActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>data.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="TextView" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="34dp" android:layout_toRightOf="@+id/textView1" android:text="TextView" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_marginTop="20dp" android:layout_toRightOf="@+id/textView1" android:text="TextView" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView4" android:layout_marginLeft="24dp" android:layout_toRightOf="@+id/textView2" android:text="TextView" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> </RelativeLayout>
package com.gusfree.weatherparse; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class WeatherParseActivity extends Activity implements OnClickListener{ TextView textView; ListView listView; InputStream is; //Date를 넣을 Collections ArrayList<Data> list =new ArrayList<Data>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViewById(R.id.button1).setOnClickListener(this); findViewById(R.id.button2).setOnClickListener(this); textView=(TextView) findViewById(R.id.textView1); listView=(ListView) findViewById(R.id.listView1); findViewById(R.id.button1).performClick();//test용 findViewById(R.id.button2).performClick();//test용 } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button1 : //날씨 정보 요청하고 응답받기 String addr ="http://www.kma.go.kr/weather/forecast/mid-term-xml.jsp?stnId=108"; try{ URL url =new URL(addr); //String -> URL //InputStream is = url.openStream(); 가장 간단한 방법 //내가 요청할 내용 HttpGet httpGet = new HttpGet(addr); //내가 고객 HttpClient client= new DefaultHttpClient(); //고객이 요청 사항을 전달하기 ->결과가 돌아옴 HttpResponse response = client.execute(httpGet); if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){//응답과 요청이 성공했다. is=response.getEntity().getContent(); /*int k=0; ByteArrayBuffer bab =new ByteArrayBuffer(64); while( (k=is.read())!=-1 ){//아스키코드 0~255 bab.append(k); } //ByteArrayBuffer -> byteArray -> String textView.setText(new String(bab.toByteArray()));*/ }else{ Toast.makeText(this,"요청중 예외발생", 0).show(); } }catch(Exception e){ } break; case R.id.button2 : //받은 데이터를 파싱해서 화면 출력 //SaxPaser로 InputStream의 데이터를 파싱하자 try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser =factory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); //InputStream -> InputSource로 형변환 하자 InputSource source = new InputSource(is); reader.setContentHandler(new ReaderWork()); reader.parse(source);//return void; /*MyThread thread =new MyThread(); thread.start();*/ } catch (Exception e) { } break; } } //리더가 할 일을 명시해둔 클래스 class ReaderWork extends DefaultHandler{ String city; String numEf; //2일후 예보 String tmEf; //날짜 태그 String wf; //날씨예보 태그 String tmn; //최저온도 태그 String tmx; //최고 온도 태그 String reliability; //신뢰도 태그 String tag; String text; @Override //xml 파싱을 시작할때 1번 호출 public void startDocument() throws SAXException { Log.w("startDocument","startDocument"); super.startDocument(); } @Override //여는 태그를 만날때 호출 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { Log.i("startElement","startElement"+localName); super.startElement(uri, localName, qName, attributes); } @Override //태그와 태그 사이의 값을 만날 때 호출 public void characters(char[] ch, int start, int length) throws SAXException { //ch ={'a','b','c','d','e','f'} => "abcde" text=new String(ch,start,length); Log.i("characters","characters"+text); super.characters(ch, start, length); } @Override //닫는 태그를 만날때 호출 public void endElement(String uri, String localName, String qName) throws SAXException { Log.w("endElement","endElement"); if(localName.equalsIgnoreCase("city")){ Log.e("city 닫는 태그","city 닫는태그 " +text); city=text; }else if(localName.equalsIgnoreCase("numEf")){ numEf=text; }else if(localName.equalsIgnoreCase("tmEf")){ tmEf=text; }else if(localName.equalsIgnoreCase("wf")){ wf=text; }else if(localName.equalsIgnoreCase("tmn")){ tmn=text; }else if(localName.equalsIgnoreCase("tmx")){ tmx=text; }else if(localName.equalsIgnoreCase("reliability")){ reliability=text; //변수 7개에 값이 들어값으므로 객체 생성 Data data = new Data(city,numEf,tmEf,wf,tmn,tmx,reliability); list.add(data); Log.e("객체생성","-----------------------------------------"); } super.endElement(uri, localName, qName); } @Override //문서 마지막에 호출 public void endDocument() throws SAXException { Log.w("endDocument","endDocument"); super.endDocument(); listView.setAdapter(new MyAdapter()); } } class MyAdapter extends BaseAdapter{ @Override public int getCount() { return list.size(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(int position, View arg1, ViewGroup arg2) { //list안에 들은 Data객체의 필득값을 //data.xml안의 뷰에 셋팅해서 return하기 Data oneData = list.get(position); RelativeLayout layout = (RelativeLayout)View.inflate(getApplicationContext(), R.layout.data, null); TextView tv1=(TextView) layout.findViewById(R.id.textView1);//도시 이름 city TextView tv2=(TextView) layout.findViewById(R.id.textView2);//날짜 tmEf TextView tv3=(TextView) layout.findViewById(R.id.textView3);//tmn~tmx TextView tv4=(TextView) layout.findViewById(R.id.textView4);//날씨 wf ImageView imgView=(ImageView) layout.findViewById(R.id.imageView1);// tv1.setText(oneData.city); tv2.setText(oneData.tmEf); tv3.setText(oneData.tmn+" ~ "+oneData.tmx); tv4.setText(oneData.wf); if(oneData.wf.contains("비")){ imgView.setImageResource(R.drawable.rainy); }else if(oneData.wf.contains("구름")){ imgView.setImageResource(R.drawable.cloudy); }else if(oneData.wf.contains("조금")){ imgView.setImageResource(R.drawable.mcloudy); } return layout; } } class MyThread extends Thread{ @Override public void run() { //할일 super.run(); } } }Data.java
package com.gusfree.weatherparse; public class Data { String city; String numEf; //2일후 예보 String tmEf; //날짜 태그 String wf; //날씨예보 태그 String tmn; //최저온도 태그 String tmx; //최고 온도 태그 String reliability; //신뢰도 태그 public Data(String city, String numEf, String tmEf, String wf, String tmn, String tmx, String reliability) { super(); this.city = city; this.numEf = numEf; this.tmEf = tmEf; this.wf = wf; this.tmn = tmn; this.tmx = tmx; this.reliability = reliability; } }
'Android > 2012.04월 강좌' 카테고리의 다른 글
11일차 DOM과 SAX의 기술적 특징 (0) | 2012.05.10 |
---|---|
11일차 오픈 API 사용법 (0) | 2012.05.10 |
11일차 Samples for SDK 사용하기 (0) | 2012.05.10 |
10일차 TouchEvent (0) | 2012.05.09 |
10일차 Login (0) | 2012.05.09 |