天气

来源:互联网 发布:淘宝定制商品能退货吗 编辑:程序博客网 时间:2024/04/29 03:29

效果图

核心代码:

WeatherAdapter.java:

public class WeatherAdapter extends ArrayAdapter<Weather>{      private int resourceId;             public WeatherAdapter(Context context, int textViewResourceId, List<Weather> objects) {          super(context, textViewResourceId, objects);          resourceId = textViewResourceId;      }        public View getView(int position,View convertView,ViewGroup viewgroup){          Weather weather = getItem(position);          ViewHolder viewHolder = null;          if (convertView == null){              viewHolder = new ViewHolder();              convertView = LayoutInflater.from(getContext()).inflate(resourceId, null);              viewHolder.tvDayOdWeek =  (TextView) convertView.findViewById(R.id.tvDayofWeek);              viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDate);                         viewHolder.tvTemperature = (TextView) convertView.findViewById(R.id.tvTemperature);              viewHolder.tvWeather = (TextView) convertView.findViewById(R.id.tvWeather);              convertView.setTag(viewHolder);                                      }else{              viewHolder= (ViewHolder) convertView.getTag();          }          viewHolder.tvDayOdWeek.setText(weather.getDayOfWeek());          viewHolder.tvDate.setText(weather.getDate());          viewHolder.tvTemperature.setText(weather.getTemperature());          viewHolder.tvWeather.setText(weather.getWeather());          return convertView;      }        private class ViewHolder{          TextView tvDayOdWeek;          TextView tvDate;          TextView tvTemperature;          TextView tvWeather;      }          }  

Weather.java

public class Weather {        private String dayOfWeek;      private String date;      private String temperature;      private String weather;      public Weather(){                }      public Weather(String dayOfWeek,String date,String temperature,              String weather){          super();          this.dayOfWeek = dayOfWeek;          this.date = date;          this.temperature = temperature;          this.weather = weather;      }      public String getDayOfWeek() {          return dayOfWeek;      }      public void setDayOfWeek(String dayOfWeek) {          this.dayOfWeek = dayOfWeek;      }      public String getDate() {          return date;      }      public void setDate(String date) {          this.date = date;      }      public String getTemperature() {          return temperature;      }      public void setTemperature(String temperature) {          this.temperature = temperature;      }      public String getWeather() {          return weather;      }      public void setWeather(String weather) {          this.weather = weather;      }            @Override      public String toString() {          // TODO Auto-generated method stub          return "Weather[dayOfWeek="+dayOfWeek+",date="+date+",temperature="                  +temperature+",weather="+weather+"]";      }  }  

HttpCallbackListener.java

public interface HttpCallbackListener {        void onFinish(String response);      void onError(Exception e);  }  


HttpUtil.java

public class HttpUtil {        public static void sendHttpRequest(final String address,final HttpCallbackListener listener){          new Thread(new Runnable() {                            @Override              public void run() {                  HttpURLConnection connection = null;                  try {                      URL url = new URL(address);                      connection = (HttpURLConnection) url.openConnection();                      connection.setRequestMethod("GET");                      connection.setReadTimeout(8000);                      connection.setConnectTimeout(8000);                      connection.setDoInput(true);                      connection.setDoOutput(true);                      InputStream in = connection.getInputStream();                      BufferedReader reader =                               new BufferedReader(new InputStreamReader(in));                      StringBuilder response = new StringBuilder();                      String line;                      while ((line = reader.readLine()) != null) {                          response.append(line);                      }                      if(listener != null){                          //回调onfinish方法                          listener.onFinish(response.toString());                                                }                  } catch (IOException e) {                      if(listener != null){                          listener.onError(e);                      }                                        }finally {                      connection.disconnect();                  }                                                  }          }).start();      }  


MainActivity.java

public class MainActivity extends Activity {        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);      }        @Override      public boolean onCreateOptionsMenu(Menu menu) {          // Inflate the menu; this adds items to the action bar if it is present.          getMenuInflater().inflate(R.menu.main, menu);          return true;      }    }  


WeatherActivity.java

public class WeatherActivity extends Activity{        private EditText etCity;      private ImageButton btnQuery;      private ListView lvFutureWeather;      public static final int SHOW_PESPONSE = 1;      private List<Weather> data;                      private void parseWithJSON(String response){              data = new ArrayList<Weather>();              JsonParser parser = new JsonParser();              JsonObject obj = (JsonObject) parser.parse(response);              //返回状态码              String resultcode = obj.get("resultcode").getAsString();              //如果状态码是200说明返回数据成功              if(resultcode != null && resultcode.equals("200")){                  JsonObject resultObj = obj.get("result").getAsJsonObject();                  JsonArray futureWeatherArray = resultObj.get("future").getAsJsonArray();                  for(int i=0;i<futureWeatherArray.size();i++){                      Weather weather = new Weather();                      JsonObject weatherObject = futureWeatherArray.get(i).getAsJsonObject();                      weather.setDayOfWeek(weatherObject.get("week").getAsString());                      weather.setDate(weatherObject.get("date").getAsString());                      weather.setTemperature(weatherObject.get("temperature").getAsString());                      weather.setWeather(weatherObject.get("weather").getAsString());                      data.add(weather);                  }              }          }                      @Override      protected void onCreate(Bundle savedInstanceState) {          // TODO Auto-generated method stub          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_weather);          setListeners();          initView();                }      private void setListeners() {          etCity = (EditText) findViewById(R.id.etCity);          btnQuery = (ImageButton) findViewById(R.id.btnQuery);          lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);                }      private void initView() {          btnQuery.setOnClickListener(new OnClickListener() {                            @Override              public void onClick(View v) {                  String city = etCity.getText().toString();                  try{                      city = URLEncoder.encode("滨州", "utf-8");//至关重要的一句                  }catch(UnsupportedEncodingException e){                      e.printStackTrace();                  }                  System.out.println("cityName=" + city);                  System.out.println("lvFutureWeather="+lvFutureWeather);                  Toast.makeText(WeatherActivity.this, "success", Toast.LENGTH_LONG).show();                  String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+city+"&key=2e0565f85c267f344e16bd5b89c55444";                  HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {                                            @Override                      public void onFinish(String response) {                          Message message = new Message();                          message.what = SHOW_PESPONSE;                          //将服务器返回的结果存放到Message中                          message.obj = response.toString();                          handler.sendMessage(message);                                                }                                            @Override                      public void onError(Exception e) {                          System.out.println("访问失败");                                                }                  });                                }          });                }        private Handler handler = new Handler(){                    public void handleMessage(android.os.Message msg) {              switch(msg.what){              case SHOW_PESPONSE:                  String response = (String) msg.obj;                  //Toast.makeText(WeatherActivity.this, response, Toast.LENGTH_LONG).show();                  System.out.println("response="+response);                  if(response != null){                      parseWithJSON(response);                      WeatherAdapter weatherAdapter = new WeatherAdapter(                              WeatherActivity.this,                              R.layout.activity_weather_listitem,data);                              lvFutureWeather.setAdapter(weatherAdapter);                              ScaleAnimation scaleAnimation = new ScaleAnimation(0,1,0,1);                              scaleAnimation.setDuration(1000);                              LayoutAnimationController animationController =                                       new LayoutAnimationController(scaleAnimation,0.6f);                              lvFutureWeather.setLayoutAnimation(animationController);                                                        }              default:                  break;              }                        }      };          }  


activity_weather.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"           android:background="@drawable/activity_weather_bg"          >          <LinearLayout               android:id="@+id/linearlayout"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:orientation="horizontal"              >              <EditText                   android:id="@+id/etCity"                  android:layout_width="0dp"                  android:layout_height="wrap_content"                  android:layout_marginLeft="10dp"                  android:layout_marginTop="20dp"                  android:layout_weight="1"                  android:background="@android:drawable/edit_text"                  android:drawableLeft="@drawable/icons_weather_city"                  android:drawablePadding="5dp"                  android:ems="10"                  android:hint="@string/etCity"                 >                 <requestFocus/>                               </EditText>                            <ImageButton                   android:id="@+id/btnQuery"                  android:layout_width="50dp"                  android:layout_height="50dp"                  android:layout_marginTop="20dp"                  android:background="@null"                  android:src="@drawable/icons_weather_query"/>          </LinearLayout>                <ListView              android:id="@+id/lvFutureWeather"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_alignParentLeft="true"              android:layout_alignParentTop="true"              android:dividerHeight="10dp"              android:layoutAnimation="@anim/weather_list_layout_animation" >          </ListView>            </RelativeLayout>  

activity_weather_listitem.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="wrap_content"          android:padding="10dp"          android:layout_margin="10dp"          android:background="@drawable/list_item_shape" >                    <TextView               android:id="@+id/tvDayofWeek"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_alignParentLeft="true"              android:layout_alignParentTop="true"              android:text="星期日"              />          <TextView               android:id="@+id/tvDate"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_alignBaseline="@+id/tvDayofWeek"              android:layout_alignBottom="@+id/tvDayofWeek"              android:layout_alignParentRight="true"              android:text="20160207"/>          <TextView               android:id="@+id/tvTemperature"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_alignLeft="@+id/tvDayofWeek"              android:layout_below="@+id/tvDayofWeek"              android:layout_marginTop="15dp"              android:text="temperature"/>          <TextView               android:id="@+id/tvWeather"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_alignLeft="@+id/tvTemperature"              android:layout_below="@+id/tvTemperature"              android:layout_marginTop="15dp"              android:text="weather"/>            </RelativeLayout>  


0 0