溫馨提示:您的每一次轉載,體現了我寫此文的意義!!!煩請您在轉載時注明出處http://www.aygfsteel.com/sxyx2008/謝謝合作!!!

          雪山飛鵠

          溫馨提示:您的每一次轉載,體現了我寫此文的意義!!!煩請您在轉載時注明出處http://www.aygfsteel.com/sxyx2008/謝謝合作!!!

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            215 Posts :: 1 Stories :: 674 Comments :: 0 Trackbacks
          DayOfWeek.java
          package com.zhy.shortcut.test;

          /**
           * 周天氣信息
           * 
          @author scott
           *
           
          */
          public class DayOfWeek {
              
          private String day_of_week;
              
          private String low;
              
          private String high;
              
          private String icon;
              
          private String info;

              
          public String getDay_of_week() {
                  
          return day_of_week;
              }

              
          public void setDay_of_week(String day_of_week) {
                  
          this.day_of_week = day_of_week;
              }

              
          public String getLow() {
                  
          return low;
              }

              
          public void setLow(String low) {
                  
          this.low = low;
              }

              
          public String getHigh() {
                  
          return high;
              }

              
          public void setHigh(String high) {
                  
          this.high = high;
              }

              
          public String getIcon() {
                  
          return icon;
              }

              
          public void setIcon(String icon) {
                  
          this.icon = icon;
              }

              
          public String getInfo() {
                  
          return info;
              }

              
          public void setInfo(String info) {
                  
          this.info = info;
              }
          }
          WeatherInfo.java
          package com.zhy.shortcut.test;

          /**
           * 天氣信息實體類
           * 
          @author scott
           *
           
          */
          public class WeatherInfo {

              
          private String city;
              
          private String time;
              
          private String weatherinfo;
              
          private String humidity;
              
          private String image;
              
          private String wind;

              
          public String getCity() {
                  
          return city;
              }

              
          public void setCity(String city) {
                  
          this.city = city;
              }

              
          public String getTime() {
                  
          return time;
              }

              
          public void setTime(String time) {
                  
          this.time = time;
              }

              
          public String getWeatherinfo() {
                  
          return weatherinfo;
              }

              
          public void setWeatherinfo(String weatherinfo) {
                  
          this.weatherinfo = weatherinfo;
              }

              
          public String getHumidity() {
                  
          return humidity;
              }

              
          public void setHumidity(String humidity) {
                  
          this.humidity = humidity;
              }

              
          public String getImage() {
                  
          return image;
              }

              
          public void setImage(String image) {
                  
          this.image = image;
              }

              
          public String getWind() {
                  
          return wind;
              }

              
          public void setWind(String wind) {
                  
          this.wind = wind;
              }

          }
          WeatherActivity.java
          package com.zhy.ui;

          import java.io.BufferedReader;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.InputStreamReader;
          import java.net.MalformedURLException;
          import java.net.URL;
          import java.net.URLConnection;
          import java.net.URLEncoder;
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.List;

          import org.json.JSONArray;
          import org.json.JSONObject;
          import org.xmlpull.v1.XmlPullParser;
          import org.xmlpull.v1.XmlPullParserFactory;

          import android.app.Activity;
          import android.content.Context;
          import android.graphics.drawable.Drawable;
          import android.os.Bundle;
          import android.os.Handler;
          import android.os.Message;
          import android.view.LayoutInflater;
          import android.view.View;
          import android.view.ViewGroup;
          import android.widget.AdapterView;
          import android.widget.AdapterView.OnItemSelectedListener;
          import android.widget.ArrayAdapter;
          import android.widget.BaseAdapter;
          import android.widget.ImageView;
          import android.widget.ListView;
          import android.widget.Spinner;
          import android.widget.TextView;

          import com.zhy.shortcut.R;
          import com.zhy.shortcut.test.DayOfWeek;
          import com.zhy.shortcut.test.WeatherInfo;

          public class WeatherActivity extends Activity {
              
              
          //當天天氣信息
              private ImageView imageView;
              
          private TextView city;
              
          private TextView time;
              
          private TextView weatherinfo;
              
          private TextView humidity;
              
          private TextView wind;
              
              List
          <String> lists=null;
              
              
              ListView listView;
              
              Spinner  spinner;
              
              
          //用于SimpleAdaper時的參數  其數據為Map中的鍵
              String[] from=new String[]{"icon","day_of_week","info","high","low"};
              
              
          //存放控件的Id
              int[] to=new int[]{R.id.icon,R.id.day_of_week,R.id.info,R.id.high,R.id.low};
              
              Handler handlercity;
              
              
              Handler handler
          =new Handler(){
                  
                  WeatherInfo info
          =null;
                  
                  List
          <DayOfWeek> list=null;
                  
                  @SuppressWarnings(
          "unchecked")
                  
          public void handleMessage(android.os.Message msg) {
                      
                      
          //從Handler中取值,msg.obj中存放的是HashMap
                      HashMap<String, Object> map=(HashMap<String, Object>) msg.obj;
                      
                      
          //從Map中獲取當前天氣信息
                      info=(WeatherInfo) map.get("info");
                      
                      
          //從Map中獲取DayOfWeek信息
                      list=(List<DayOfWeek>) map.get("list");
                      
                      
          //設置當前天氣信息
                      try {
                          imageView.setImageDrawable(Drawable.createFromStream(
          new URL(info.getImage()).openStream(), null));
                      } 
          catch (MalformedURLException e) {
                          e.printStackTrace();
                      } 
          catch (IOException e) {
                          e.printStackTrace();
                      }
                      
                      city.setText(info.getCity());
                      weatherinfo.setText(info.getWeatherinfo());
                      humidity.setText(info.getHumidity());
                      wind.setText(info.getWind());
                      time.setText(info.getTime());
                      
                      
                      
          //使用SimpleAdapter方式來處理天氣數據
                      /*
                      List<HashMap<String, String>> lsit=new ArrayList<HashMap<String,String>>();
                      
                      HashMap<String, String> maps=null;
                      
                      for (DayOfWeek week : list) {
                          maps=new HashMap<String, String>();
                          maps.put("day_of_week", week.getDay_of_week());
                          maps.put("info", week.getInfo());
                          maps.put("icon", week.getIcon());
                          maps.put("high", week.getHigh());
                          maps.put("low", week.getLow());
                          lsit.add(maps);
                      }
          */
                      
                      
                      
          //listView.setAdapter(new SimpleAdapter(WeatherActivity.this,lsit,R.layout.weatherlst,from,to));
                      
                      
          //使用自定義的Adaper處理天氣信息
                      listView.setAdapter(new WeatherAdapter(WeatherActivity.this,list));
                      
                  };
              };
              
              
              
              
              Handler spanhandler
          =new Handler(){
                  
                  WeatherInfo info
          =null;
                  
                  List
          <DayOfWeek> list=null;
                  
                  @SuppressWarnings(
          "unchecked")
                  
          public void handleMessage(Message msg) {
                      
          //從Handler中取值,msg.obj中存放的是HashMap
                      HashMap<String, Object> map=(HashMap<String, Object>) msg.obj;
                      
                      
          //從Map中獲取當前天氣信息
                      info=(WeatherInfo) map.get("info");
                      
                      
          //從Map中獲取DayOfWeek信息
                      list=(List<DayOfWeek>) map.get("list");
                      
                      
          //設置當前天氣信息
                      try {
                          imageView.setImageDrawable(Drawable.createFromStream(
          new URL(info.getImage()).openStream(), null));
                      } 
          catch (MalformedURLException e) {
                          e.printStackTrace();
                      } 
          catch (IOException e) {
                          e.printStackTrace();
                      }
                      
                      city.setText(info.getCity());
                      weatherinfo.setText(info.getWeatherinfo());
                      humidity.setText(info.getHumidity());
                      wind.setText(info.getWind());
                      time.setText(info.getTime());
                      
                      
          //使用自定義的Adaper處理天氣信息
                      listView.setAdapter(new WeatherAdapter(WeatherActivity.this,list));
                      
                  }
              };
              
              
              
              
              
          /**
               * 自定義的Adaper
               * 
          @author scott
               *
               
          */
              
          class WeatherAdapter extends BaseAdapter{

                  List
          <DayOfWeek> list;
                  
                  
          public List<DayOfWeek> getList() {
                      
          return list;
                  }

                  
          public void setList(List<DayOfWeek> list) {
                      
          this.list = list;
                  }

                  Context context;
                  
                  
          public WeatherAdapter() {
                      
                  }
                  
                  
          public WeatherAdapter(Context context,List<DayOfWeek> list) {
                      
          super();
                      
          this.context = context;
                      
          this.list=list;
                  }



                  @Override
                  
          public int getCount() {
                      
          return list.size();
                  }

                  @Override
                  
          public Object getItem(int position) {
                      
          return list.get(position);
                  }

                  @Override
                  
          public long getItemId(int position) {
                      
          return position;
                  }

                  
                  
          //重點是這個方法
                  @Override
                  
          public View getView(int position, View convertView, ViewGroup parent) {
                      
                      
          //使用LayoutInflater加載xml布局文件
                      
                      convertView 
          = LayoutInflater.from(context).inflate(R.layout.weatherlst,null);
                      
                      
          //查找控件 注意是從convertView中查找即新加載的xml布局文件中查找
                      ImageView viewImageView = (ImageView) convertView.findViewById(R.id.icon);
                      TextView day_of_week
          =(TextView) convertView.findViewById(R.id.day_of_week);
                      TextView info
          =(TextView) convertView.findViewById(R.id.info);
                      TextView high
          =(TextView) convertView.findViewById(R.id.high);
                      TextView low
          =(TextView) convertView.findViewById(R.id.low);
                      
                      
          //設置數據
                      try {
                          viewImageView.setImageDrawable(Drawable.createFromStream(
          new URL(list.get(position).getIcon()).openStream(), null));
                      } 
          catch (MalformedURLException e) {
                          e.printStackTrace();
                      } 
          catch (IOException e) {
                          e.printStackTrace();
                      }
                      
                      day_of_week.setText(list.get(position).getDay_of_week());
                      info.setText(list.get(position).getInfo());
                      high.setText(list.get(position).getHigh());
                      low.setText(list.get(position).getLow());
                      
                      
          //返回view
                      return convertView;
                  }
                  
              }
              
              
              
              @Override
              
          protected void onCreate(Bundle savedInstanceState) {
                  
          super.onCreate(savedInstanceState);
                  
                  setContentView(R.layout.weather);
                  
                  imageView
          =(ImageView) findViewById(R.id.todayimg);
                  city
          =(TextView) findViewById(R.id.city);
                  time
          =(TextView) findViewById(R.id.time);
                  weatherinfo
          =(TextView) findViewById(R.id.weatherinfo);
                  humidity
          =(TextView) findViewById(R.id.humidity);
                  wind
          =(TextView) findViewById(R.id.wind);
                  
                  
                  spinner
          =(Spinner) findViewById(R.id.cities);
                  
                  
                  listView
          =(ListView) findViewById(R.id.lst);
                  
                  
                  spinner.setOnItemSelectedListener(
          new OnItemSelectedListener() {
                      
                      String city;
                      
                      @Override
                      
          public void onItemSelected(AdapterView<?> parent, View view,
                              
          int position, long id) {
                          spanhandler.postDelayed(
          new Runnable() {
                              
          //調用解析天氣預報的代碼
                              @Override
                              
          public void run() {
                                  
                                  city
          =spinner.getSelectedItem().toString();
                                  
                                  String urlString
          ="http://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode(city);;
                                  
                                  
          try {
                                      URL url
          =new URL(urlString);
                                      
                                      
          try {
                                          URLConnection connection
          =url.openConnection();
                                          InputStream inputStream 
          = connection.getInputStream();
                                          
          try {
                                              
                                              
          //調用Google天氣預報解析方法
                                              HashMap<String, Object> map = parse(inputStream);
                                              
                                              Message msg
          =new Message();
                                              
                                              
          //傳遞數據
                                              msg.obj=map;
                                              
                                              
          //發送消息
                                              handler.sendMessage(msg);
                                              
                                              
                                          } 
          catch (Exception e) {
                                              e.printStackTrace();
                                          }
                                      } 
          catch (IOException e) {
                                          e.printStackTrace();
                                      }
                                  } 
          catch (MalformedURLException e) {
                                      e.printStackTrace();
                                  }
                              }
                          },
          2000);
                      }

                      @Override
                      
          public void onNothingSelected(AdapterView<?> parent) {
                          
                      }
                      
                  });
                  
                  
                  handlercity
          =new Handler();
                  
                  handlercity.post(
          new Runnable() {
                      
                      @Override
                      
          public void run() {
                          
          try {
                              lists 
          = parse();
                          } 
          catch (Exception ex) {
                              ex.printStackTrace();
                          }
                          
          //創建adapter
                          ArrayAdapter<String> adapter=new ArrayAdapter<String>(WeatherActivity.this, android.R.layout.simple_spinner_item, lists);
                          spinner.setAdapter(adapter);
                          
          //查找西安的位置
                          int position=lists.indexOf("西安");
                          
          //設置默認選中西安
                          spinner.setSelection(position);
                          
          //設置下拉列別的樣式
                          adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                          
                      }
                  });
                  
                  handler.post(
          new Runnable() {
                      
          //調用解析天氣預報的代碼
                      @Override
                      
          public void run() {
                          String urlString
          ="http://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode("西安");
                          
          try {
                              URL url
          =new URL(urlString);
                              
                              
          try {
                                  URLConnection connection
          =url.openConnection();
                                  InputStream inputStream 
          = connection.getInputStream();
                                  
          try {
                                      
                                      
          //調用Google天氣預報解析方法
                                      HashMap<String, Object> map = parse(inputStream);
                                      
                                      Message msg
          =new Message();
                                      
                                      
          //傳遞數據
                                      msg.obj=map;
                                      
                                      
          //發送消息
                                      handler.sendMessage(msg);
                                      
                                      
                                  } 
          catch (Exception e) {
                                      e.printStackTrace();
                                  }
                              } 
          catch (IOException e) {
                                  e.printStackTrace();
                              }
                          } 
          catch (MalformedURLException e) {
                              e.printStackTrace();
                          }
                      }
                  });
              }
              
              
              
              
              
          /**
               * 解析Goole天氣預報返回的xml數據
               * 
          @param inputStream
               * 
          @throws Exception
               
          */
              
          private HashMap<String, Object> parse(InputStream inputStream) throws Exception {
                  
                  WeatherInfo info
          =null;
                  
                  DayOfWeek dayOfWeek
          =null;
                  
                  List
          <DayOfWeek> list=null;
                  
                  HashMap
          <String, Object> map=new HashMap<String, Object>();
                  
                  
          boolean isFirst=true;
                  
                  XmlPullParserFactory factory 
          = XmlPullParserFactory.newInstance(); 
                  XmlPullParser parser 
          = factory.newPullParser();
                  parser.setInput(inputStream, 
          "gbk");
                  
                  
          int eventType=parser.getEventType();
                  
          while(eventType!=XmlPullParser.END_DOCUMENT){
                      
                      String nodename
          =parser.getName();
                      
                      
          switch (eventType) {
                      
          case XmlPullParser.START_DOCUMENT:
                          list
          =new ArrayList<DayOfWeek>();
                      
          case XmlPullParser.START_TAG:
                          
                          
          if(isFirst){
                              
          if("forecast_information".equals(nodename)){
                                  info
          =new WeatherInfo();
                              }
                              
          if("city".equals(nodename)){
                                  info.setCity(parser.getAttributeValue(
          0));
                              }
          if("forecast_date".equals(nodename)){
                                  info.setTime(parser.getAttributeValue(
          0));
                              }
          if("condition".equals(nodename)){
                                  info.setWeatherinfo(parser.getAttributeValue(
          0));
                              }
          if("humidity".equals(nodename)){
                                  info.setHumidity(parser.getAttributeValue(
          0));
                              }
          if("icon".equals(nodename)){
                                  info.setImage(
          "http://www.google.com"+parser.getAttributeValue(0));
                              }
          if("wind_condition".equals(nodename)){
                                  info.setWind(parser.getAttributeValue(
          0));
                              }
                          }
          else{
                              
          if("forecast_conditions".equals(nodename)){
                                  dayOfWeek
          =new DayOfWeek();
                              }
                              
          if("day_of_week".equals(nodename)){
                                  dayOfWeek.setDay_of_week(parser.getAttributeValue(
          0));
                              }
          if("low".equals(nodename)){
                                  dayOfWeek.setLow(parser.getAttributeValue(
          0));
                              }
          if("high".equals(nodename)){
                                  dayOfWeek.setHigh(parser.getAttributeValue(
          0));
                              }
          if("icon".equals(nodename)){
                                  dayOfWeek.setIcon(
          "http://www.google.com"+parser.getAttributeValue(0));
                              }
          if("condition".equals(nodename)){
                                  dayOfWeek.setInfo(parser.getAttributeValue(
          0));
                              }
                          }
                          
          break;
                      
          case XmlPullParser.END_TAG:
                          
          if("current_conditions".equals(nodename)){
                              isFirst
          =false;
                          }
                          
          if("forecast_conditions".equals(nodename)){
                              list.add(dayOfWeek);
                          }
                          
          break;
                      
          default:
                          
          break;
                      }
                      eventType
          =parser.next();
                  }
                  
                  map.put(
          "info", info);
                  map.put(
          "list", list);
                  
                  
          return map;
              }
              
              
              
              
              
              
          /**
               * 解析城市
               * 
          @return
               * 
          @throws Exception
               
          */
              
          private List<String> parse() throws Exception{
                  
                  List
          <String> list=new ArrayList<String>();
                  
                  String urlString 
          = "http://www.google.com/ig/cities?country=cn&hl=zh-cn";
                  
                  URL url
          =new URL(urlString);
                  InputStream  inputStream
          = url.openStream();
                  StringBuilder json
          =new StringBuilder();
                  
                  String str;
                  BufferedReader reader
          =new BufferedReader(new InputStreamReader(inputStream,"gbk"));
                  
                  
          while((str=reader.readLine())!=null){
                      json.append(str);
                  }
                  
                  JSONObject jsonObject
          =new JSONObject(json.toString());
                  JSONArray array 
          = jsonObject.getJSONArray("cities");
                  
          for (int i = 0; i < array.length(); i++) {
                      JSONObject object
          =new JSONObject(array.getString(i));
                      String citys 
          = (String)object.get("name");
                      list.add(citys);
                  }
                  
                  reader.close();
                  inputStream.close();
                  
                  
          return list;
              }
              
              
          }
          weather.xml
          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width
          ="match_parent"
              android:layout_height
          ="match_parent"
              android:orientation
          ="vertical" >

              
          <LinearLayout 
                  
          android:layout_width="match_parent"
                  android:layout_height
          ="wrap_content"
                  android:orientation
          ="vertical"
                  
          >
                  
          <Spinner 
                      
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/cities"
                      
          />
                  
          <ImageView 
                      
          android:layout_width="wrap_content"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/todayimg"
                      
          />
                  
          <TextView 
                      
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/city"
                      
          />
                  
          <TextView 
                      
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/time"
                      
          />
                  
          <TextView 
                      
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/weatherinfo"
                      
          />
                  
          <TextView 
                     
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:id
          ="@+id/humidity"
                      
          />
                  
          <TextView 
                     
          android:layout_width="match_parent"
                     android:layout_height
          ="wrap_content"
                     android:id
          ="@+id/wind"
                      
          />
              
          </LinearLayout>
              
              
          <ListView 
                  
          android:layout_width="match_parent"
                  android:layout_height
          ="wrap_content"
                  android:id
          ="@+id/lst"
                  
          >
              
          </ListView>
              

          </LinearLayout>
          weatherlst.xml
          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width
          ="match_parent"
              android:layout_height
          ="match_parent"
              android:orientation
          ="horizontal" >

              
          <RelativeLayout
                  
          android:layout_width="match_parent"
                  android:layout_height
          ="wrap_content" 
                  android:layout_gravity
          ="center"
                  
          >

                  
          <ImageView
                      
          android:paddingLeft="50dip"
                      android:id
          ="@+id/icon"
                      android:layout_width
          ="wrap_content"
                      android:layout_height
          ="wrap_content" />

                  
          <LinearLayout
                      
          android:layout_width="match_parent"
                      android:layout_height
          ="wrap_content"
                      android:orientation
          ="horizontal" 
                      android:layout_toRightOf
          ="@id/icon"
                      android:paddingLeft
          ="10dip"
                      android:paddingTop
          ="10dip">

                      
          <TextView
                          
          android:id="@+id/day_of_week"
                          android:layout_width
          ="wrap_content"
                          android:layout_height
          ="wrap_content"
                          android:gravity
          ="center"
                          android:paddingLeft
          ="10dip" />

                      
          <TextView
                          
          android:id="@+id/info"
                          android:layout_width
          ="wrap_content"
                          android:layout_height
          ="wrap_content"
                          android:gravity
          ="center"
                          android:paddingLeft
          ="10dip" />

                      
          <TextView
                          
          android:id="@+id/low"
                          android:layout_width
          ="wrap_content"
                          android:layout_height
          ="wrap_content"
                          android:gravity
          ="center"
                          android:paddingLeft
          ="10dip" />

                      
          <TextView
                          
          android:id="@+id/high"
                          android:layout_width
          ="wrap_content"
                          android:layout_height
          ="wrap_content"
                          android:gravity
          ="center"
                          android:paddingLeft
          ="10dip" />
                  
          </LinearLayout>
              
          </RelativeLayout>

          </LinearLayout>
          程序運行截圖
          posted on 2011-12-16 17:54 雪山飛鵠 閱讀(1952) 評論(1)  編輯  收藏 所屬分類: android

          Feedback

          # re: Android小應用之Google天氣預報[未登錄] 2012-09-06 14:24 111
          怎么adapter 那顯示空指針異常。。。?  回復  更多評論
            

          主站蜘蛛池模板: 汉源县| 哈尔滨市| 内乡县| 托克逊县| 新河县| 新巴尔虎右旗| 德庆县| 仙游县| 柘城县| 万安县| 江孜县| 木里| 吴川市| 巴楚县| 宁都县| 个旧市| 通州区| 进贤县| 吉首市| 柳州市| 湟源县| 福泉市| 米泉市| 青龙| 科技| 理塘县| 梅州市| 高碑店市| 伊通| 仁布县| 保康县| 江源县| 南投市| 麻江县| 会同县| 武邑县| 九江县| 谷城县| 南华县| 清水河县| 沅陵县|