概述
今天主要跟大家分享一下如何从API中获取数据,顺便写了一个小的例子,天气情况的获取。数据来源是聚合数据,网址给大家,可以去看看~
聚合数据 https://www.juhe.cn/
天气预报数据信息 https://www.juhe.cn/docs/api/id/39
界面啥的,直接看主页面好了,主要是这样的:
多的也不说了,直接上代码好了,希望大家可以在这种粗暴的方式中,慢慢的享受~~~
首先,界面的xml,其实这个没什么好说的,但是可以看看空间的名字啥的,还有就是我的界面写的忒丑,需要大家的鞭策啊~~~
界面:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/ll_main_container"
android:layout_width="match_parent"
android:layout_height="280dp"
android:background="@drawable/sun"
android:orientation="vertical"
android:padding="12dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/ib_city"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/position" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<TextView
android:id="@+id/tv_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingTop="20dp"
android:text="北京"
android:textColor="#ffffff"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_temperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingTop="22dp"
android:text="11度"
android:textColor="#ffffff"
android:textSize="28dp" />
<TextView
android:id="@+id/tv_weather"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingTop="12dp"
android:text="小雨"
android:textColor="#ffffff"
android:textSize="15dp" />
<TextView
android:id="@+id/tv_wind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingBottom="32dp"
android:paddingTop="12dp"
android:text="东北风 2级"
android:textColor="#ffffff"
android:textSize="15dp" />
<TextView
android:id="@+id/tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:paddingBottom="2dp"
android:paddingTop="18dp"
android:text="2015年10月1日星期一"
android:textColor="#ffffff"
android:textSize="12dp" />
</LinearLayout>
<GridView
android:id="@+id/gv_forweather"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="@+id/ll_main_container"
android:numColumns="5"
android:paddingBottom="10dp"
android:paddingTop="10dp" >
</GridView>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="@drawable/b"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/ib_life"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/life" />
</LinearLayout>
<TextView
android:id="@+id/tv_net"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="47dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="20dp"
android:textColor="#cccccc"
android:textSize="15dp" />
</RelativeLayout>
实体类的设计,主要是保存天气的信息,具体的设计要根据自己获取到的数据内容来进行设计,这里我读出了获取的所有信息(json解析),只是为了给大家做一个例子,实际的应用中,需要什么数据,解析什么数据即可,不必逐一的将其解析。
实体类:
package cn.yurui.weather.entity;
import java.util.ArrayList;
public class Weather {
/**
* 返回码
*/
private int code;
/**
* 返回说明
*/
private String reason;
/**
* 当前城市
*/
private String city_name;
/**
* 当前时间
*/
private String date;
private String week;
private String moon;
/**
* 更新时间
*/
private String update_time;
/**
* 当前实际天气
*/
private Weatherinfo weather;
public static class Weatherinfo {
/**
* 温度
*/
private String temperature;
/**
* 湿度
*/
private String Humidity;
/**
* 雾
*/
private String info;
/**
* img
*/
private String img;
// 各种getter与setter
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getHumidity() {
return Humidity;
}
public void setHumidity(String humidity) {
Humidity = humidity;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
@Override
public String toString() {
return "Weatherinfo [temperature=" + temperature + ", Humidity="
+ Humidity + ", info=" + info + ", img=" + img + "]";
}
}
/**
* 风
*/
private Wind wind;
public static class Wind {
/**
* 风向
*/
private String direct;
/**
* 风级
*/
private String power;
// 各种getter与setter
public String getDirect() {
return direct;
}
public void setDirect(String direct) {
this.direct = direct;
}
public String getPower() {
return power;
}
public void setPower(String power) {
this.power = power;
}
@Override
public String toString() {
return "Wind [direct=" + direct + ", power=" + power + "]";
}
}
/**
* 生活指数
*/
private Life life;
public static class Life {
/**
* 穿衣指数
*/
private String wear;
private String wear1;
/**
* 感冒指数
*/
private String ill;
private String ill1;
/**
* 空调指数
*/
private String air_condition;
private String air_condition1;
/**
* 污染指数
*/
private String polution;
private String polution1;
/**
* 洗车指数
*/
private String clean_car;
private String clean_car1;
/**
* 运动指数
*/
private String sport;
private String sport1;
/**
*
* 紫外线
*/
private String light;
private String light1;
// 各种getter与setter
public String getWear() {
return wear;
}
public void setWear(String wear) {
this.wear = wear;
}
public String getIll() {
return ill;
}
public void setIll(String ill) {
this.ill = ill;
}
public String getAir_condition() {
return air_condition;
}
public void setAir_condition(String air_condition) {
this.air_condition = air_condition;
}
public String getPolution() {
return polution;
}
public void setPolution(String polution) {
this.polution = polution;
}
public String getClean_car() {
return clean_car;
}
public void setClean_car(String clean_car) {
this.clean_car = clean_car;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getLight() {
return light;
}
public void setLight(String light) {
this.light = light;
}
public String getWear1() {
return wear1;
}
public void setWear1(String wear1) {
this.wear1 = wear1;
}
public String getIll1() {
return ill1;
}
public void setIll1(String ill1) {
this.ill1 = ill1;
}
public String getAir_condition1() {
return air_condition1;
}
public void setAir_condition1(String air_condition1) {
this.air_condition1 = air_condition1;
}
public String getPolution1() {
return polution1;
}
public void setPolution1(String polution1) {
this.polution1 = polution1;
}
public String getClean_car1() {
return clean_car1;
}
public void setClean_car1(String clean_car1) {
this.clean_car1 = clean_car1;
}
public String getSport1() {
return sport1;
}
public void setSport1(String sport1) {
this.sport1 = sport1;
}
public String getLight1() {
return light1;
}
public void setLight1(String light1) {
this.light1 = light1;
}
@Override
public String toString() {
return "Life [wear=" + wear + ", wear1=" + wear1 + ", ill=" + ill
+ ", ill1=" + ill1 + ", air_condition=" + air_condition
+ ", air_condition1=" + air_condition1 + ", polution="
+ polution + ", polution1=" + polution1 + ", clean_car="
+ clean_car + ", clean_car1=" + clean_car1 + ", sport="
+ sport + ", sport1=" + sport1 + ", light=" + light
+ ", light1=" + light1 + "]";
}
}
/**
* 未来几天的天气状况
*/
private ArrayList<Forweather> forweathers;
public static class Forweather {
/**
* 日期
*/
String week;
String moon;
String fordate;
/**
* 白天的天气
*/
String day_weather;
String day_hightem;
String day_wind;
String day_power;
/**
* 晚上的天气
*/
String night_weather;
String night_hightem;
String night_wind;
String night_power;
public String getFordate() {
return fordate;
}
public void setFordate(String fordate) {
this.fordate = fordate;
}
public String getDay_weather() {
return day_weather;
}
public void setDay_weather(String day_weather) {
this.day_weather = day_weather;
}
public String getDay_hightem() {
return day_hightem;
}
public void setDay_hightem(String day_hightem) {
this.day_hightem = day_hightem;
}
public String getDay_wind() {
return day_wind;
}
public void setDay_wind(String day_wind) {
this.day_wind = day_wind;
}
public String getDay_power() {
return day_power;
}
public void setDay_power(String day_power) {
this.day_power = day_power;
}
public String getNight_weather() {
return night_weather;
}
public void setNight_weather(String night_weather) {
this.night_weather = night_weather;
}
public String getNight_hightem() {
return night_hightem;
}
public void setNight_hightem(String night_hightem) {
this.night_hightem = night_hightem;
}
public String getNight_wind() {
return night_wind;
}
public void setNight_wind(String night_wind) {
this.night_wind = night_wind;
}
public String getNight_power() {
return night_power;
}
public void setNight_power(String night_power) {
this.night_power = night_power;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getMoon() {
return moon;
}
public void setMoon(String moon) {
this.moon = moon;
}
@Override
public String toString() {
return "Forweather [week=" + week + ", moon=" + moon + ", fordate="
+ fordate + ", day_weather=" + day_weather
+ ", day_hightem=" + day_hightem + ", day_wind=" + day_wind
+ ", day_power=" + day_power + ", night_weather="
+ night_weather + ", night_hightem=" + night_hightem
+ ", night_wind=" + night_wind + ", night_power="
+ night_power + "]";
}
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getMoon() {
return moon;
}
public void setMoon(String moon) {
this.moon = moon;
}
public String getUpdate_time() {
return update_time;
}
public void setUpdate_time(String update_time) {
this.update_time = update_time;
}
public Weatherinfo getWeather() {
return weather;
}
public void setWeather(Weatherinfo weather) {
this.weather = weather;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Life getLife() {
return life;
}
public void setLife(Life life) {
this.life = life;
}
public ArrayList<Forweather> getForweathers() {
return forweathers;
}
public void setForweathers(ArrayList<Forweather> forweathers) {
this.forweathers = forweathers;
}
public int getCode() {
return code;
}
public void setCode(int string) {
this.code = string;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
/**
* pm值
*/
private Pm pm;
public Pm getPm() {
return pm;
}
public void setPm(Pm pm) {
this.pm = pm;
}
public static class Pm{
private String key;
private String show_desc;
private String dateTime;
private String cityName;
private InnerPm ipm;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getShow_desc() {
return show_desc;
}
public void setShow_desc(String show_desc) {
this.show_desc = show_desc;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public InnerPm getIpm() {
return ipm;
}
public void setIpm(InnerPm ipm) {
this.ipm = ipm;
}
@Override
public String toString() {
return "Pm [key=" + key + ", show_desc=" + show_desc
+ ", dateTime=" + dateTime + ", cityName=" + cityName
+ ", ipm=" + ipm + "]";
}
}
public static class InnerPm{
private String curPm;
private String pm25;
private String pm10;
private String level;
private String quality;
private String des;
public String getCurPm() {
return curPm;
}
public void setCurPm(String curPm) {
this.curPm = curPm;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
public String getPm10() {
return pm10;
}
public void setPm10(String cur10) {
this.pm10 = cur10;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
@Override
public String toString() {
return "InnerPm [curPm=" + curPm + ", pm25=" + pm25 + ", cur10="
+ pm10 + ", level=" + level + ", quality=" + quality
+ ", des=" + des + "]";
}
}
@Override
public String toString() {
return "Weather [code=" + code + ", reason=" + reason + ", city_name="
+ city_name + ", date=" + date + ", week=" + week + ", moon="
+ moon + ", update_time=" + update_time + ", weather="
+ weather + ", wind=" + wind + ", life=" + life
+ ", forweathers=" + forweathers + ", pm=" + pm + "]";
}
}
具体的天气情况的获取,最后得到的信息,封装成一个Weather对象,显示的信息从该对象中获取
根据城市的名字,获取天气的情况:
package cn.yurui.weather.dao;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import android.util.Log;
import cn.yurui.weather.entity.Weather;
import cn.yurui.weather.entity.Weather.Forweather;
import cn.yurui.weather.entity.Weather.InnerPm;
import cn.yurui.weather.entity.Weather.Life;
import cn.yurui.weather.entity.Weather.Pm;
import cn.yurui.weather.entity.Weather.Weatherinfo;
import cn.yurui.weather.entity.Weather.Wind;
public class WeatherInfoDao {
/**
* 根据输入的城市名字字符串,得到该城市相关的天气状况
*
* 联网获取信息,
*
* @throws Exception
*
*/
public static Weather getWeatherInfo(String city) {
Weather weather = new Weather();
String uri = "http://op.juhe.cn/onebox/weather/query?cityname=" + city
+ "&key=9e6f9f89e0434c133fc1ddd965729b64";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity);
// 开始解析
JSONObject jObj = new JSONObject(json);
// 获取返回结果中的reason中的信息,并封装到返回对象
weather.setReason(jObj.getString("reason"));
// 获取返回结果中的error_code中的信息,并封装到返回对象
weather.setCode(jObj.getInt("error_code"));
// 获取返回结果中的result中的信息,并封装到返回对象
String JobjResult = jObj.getString("result");
// Log.d("woshihouruixian",
// JobjResult+"woshihouruixian"+JobjResult.length());
if (JobjResult != null && JobjResult.length() > 4) {
JSONObject jR = jObj.getJSONObject("result");
JSONObject jResult = jR.getJSONObject("data");
/**
* 开始获取信息
*/
weather.setCity_name(city);
JSONObject jWeather = jResult.getJSONObject("realtime");
weather.setDate(jWeather.getString("date"));
weather.setUpdate_time(jWeather.getString("time"));
weather.setWeek(jWeather.getString("week"));
weather.setMoon(jWeather.getString("moon"));
/**
* WeatherInfo
*/
Weather.Weatherinfo weatherinfo = new Weatherinfo();
JSONObject jWeatherinfo = jWeather.getJSONObject("weather");
weatherinfo.setTemperature(jWeatherinfo
.getString("temperature"));
weatherinfo.setHumidity(jWeatherinfo.getString("humidity"));
weatherinfo.setInfo(jWeatherinfo.getString("info"));
weatherinfo.setImg(jWeatherinfo.getString("img"));
weather.setWeather(weatherinfo);
/**
* Wind
*/
Weather.Wind wind = new Wind();
JSONObject jWind = jWeather.getJSONObject("wind");
wind.setDirect(jWind.getString("direct"));
wind.setPower(jWind.getString("power"));
weather.setWind(wind);
/**
* Life
*/
Weather.Life life = new Life();
JSONObject jLife = jResult.getJSONObject("life");
JSONObject jLifeInfo = jLife.getJSONObject("info");
JSONArray jLifeWear = jLifeInfo.getJSONArray("chuanyi");
life.setWear(jLifeWear.getString(0));
life.setWear1(jLifeWear.getString(1));
JSONArray jLifeIll = jLifeInfo.getJSONArray("ganmao");
life.setIll(jLifeIll.getString(0));
life.setIll1(jLifeIll.getString(1));
JSONArray jLifeAir = jLifeInfo.getJSONArray("kongtiao");
life.setAir_condition(jLifeAir.getString(0));
life.setAir_condition1(jLifeAir.getString(1));
JSONArray jLifePolution = jLifeInfo.getJSONArray("wuran");
life.setPolution(jLifePolution.getString(0));
life.setPolution1(jLifePolution.getString(1));
JSONArray jLifeClean = jLifeInfo.getJSONArray("xiche");
life.setClean_car(jLifeClean.getString(0));
life.setClean_car1(jLifeClean.getString(1));
JSONArray jLifeSport = jLifeInfo.getJSONArray("yundong");
life.setSport(jLifeSport.getString(0));
life.setSport1(jLifeSport.getString(1));
JSONArray jLifeLight = jLifeInfo.getJSONArray("ziwaixian");
life.setLight(jLifeLight.getString(0));
life.setLight1(jLifeLight.getString(1));
weather.setLife(life);
/**
* forWeather
*/
ArrayList<Weather.Forweather> forweathers = new ArrayList<Weather.Forweather>();
JSONArray jForWeather = jResult.getJSONArray("weather");
for (int i = 0; i < jForWeather.length(); i++) {
Weather.Forweather forweather = new Forweather();
JSONObject ForweatherObj = jForWeather.getJSONObject(i);
forweather.setFordate(ForweatherObj.getString("date"));
forweather.setWeek(ForweatherObj.getString("week"));
forweather.setMoon(ForweatherObj.getString("nongli"));
JSONObject ForWeather = ForweatherObj.getJSONObject("info");
JSONArray ForWeatherInfo1 = ForWeather.getJSONArray("day");
forweather.setDay_weather(ForWeatherInfo1.getString(1));
forweather.setDay_hightem(ForWeatherInfo1.getString(2));
forweather.setDay_wind(ForWeatherInfo1.getString(3));
forweather.setDay_power(ForWeatherInfo1.getString(4));
JSONArray ForWeatherInfo2 = ForWeather
.getJSONArray("night");
forweather.setNight_weather(ForWeatherInfo2.getString(1));
forweather.setNight_hightem(ForWeatherInfo2.getString(2));
forweather.setNight_wind(ForWeatherInfo2.getString(3));
forweather.setNight_power(ForWeatherInfo2.getString(4));
forweathers.add(forweather);
}
weather.setForweathers(forweathers);
JSONObject jPm = jResult.getJSONObject("pm25");
Pm pm = new Pm();
JSONObject jPm25 = jPm.getJSONObject("pm25");
InnerPm ipm = new InnerPm();
ipm.setCurPm(jPm25.getString("curPm"));
ipm.setPm25(jPm25.getString("pm25"));
ipm.setPm10(jPm25.getString("pm10"));
ipm.setLevel(jPm25.getString("level"));
ipm.setQuality(jPm25.getString("quality"));
ipm.setDes(jPm25.getString("des"));
pm.setKey(jPm.getString("key"));
pm.setShow_desc(jPm.getString("show_desc"));
pm.setIpm(ipm);
pm.setDateTime(jPm.getString("dateTime"));
pm.setCityName(jPm.getString("cityName"));
weather.setPm(pm);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return weather;
}
}
写到这里,最主要的事情已经做完了,再就是拿数据进行显示的非常简单的事情了~由于我的项目设计到了数据的共享使用,于是我写了一个Application,但是呢就是非常简单的通过刚刚咱写的那个方法,获取一下城市天气信息,我就不贴过来了。。。
下面直接上主页面的代码了:
Adapter:
package cn.yurui.weather.adapter;
import java.util.ArrayList;
import cn.yurui.weather.R;
import cn.yurui.weather.entity.Weather;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ForWeatherAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Weather.Forweather> forweathers;
public ForWeatherAdapter(Context context,
ArrayList<Weather.Forweather> forweathers) {
this.forweathers = forweathers;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return forweathers.size() - 2;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Hodler hodler;
if (convertView == null) {
hodler = new Hodler();
convertView = inflater.inflate(R.layout.forweather_item, null);
hodler.iv_image = (ImageView) convertView
.findViewById(R.id.iv_item_image);
hodler.tv_date = (TextView) convertView
.findViewById(R.id.for_item_date);
hodler.tv_temperature = (TextView) convertView
.findViewById(R.id.for_item_temperature);
hodler.tv_weather=(TextView) convertView.findViewById(R.id.tv_weather);
convertView.setTag(hodler);
} else {
hodler = (Hodler) convertView.getTag();
}
Weather.Forweather forweather = forweathers.get(position);
if (position == 0) {
hodler.tv_date.setText("今天");
} else if (position == 1) {
hodler.tv_date.setText("明天");
} else {
hodler.tv_date.setText("星期"+forweather.getWeek());
}
hodler.tv_temperature.setText(forweather.getNight_hightem() + "~"
+ forweather.getDay_hightem() + "度");
hodler.tv_weather.setText(forweather.getDay_weather());
return convertView;
}
private class Hodler {
private TextView tv_date, tv_temperature,tv_weather;
private ImageView iv_image;
}
}
主页面代码:
package cn.yurui.weather.activity;
import java.util.ArrayList;
import cn.yurui.weather.R;
import cn.yurui.weather.R.id;
import cn.yurui.weather.adapter.ForWeatherAdapter;
import cn.yurui.weather.app.MyWeatherApplication;
import cn.yurui.weather.dao.WeatherInfoDao;
import cn.yurui.weather.entity.Weather;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class MainActivity extends Activity implements OnClickListener {
private Handler handler;
private MyWeatherApplication application;
/**
* 声明控件
*/
private LinearLayout ll_main_container;
private TextView tv_city, tv_temperature, tv_weather, tv_wind, tv_date,
tv_net;
private GridView gv_forweather;
private ImageButton ib_life, ib_city;
/**
* 得到数据源
*
*/
// 未来几天的天气状况
private ArrayList<Weather.Forweather> forweathers = new ArrayList<Weather.Forweather>();
// 本次查询的所有数据整合
private Weather weather;
// 查询数据的工具
private WeatherInfoDao dao;
private ForWeatherAdapter adapter;
private String city;
/**
* 用户偏好设置,保存用户输入当前定位
*/
private SharedPreferences preferences;
private Editor editor;
/**
* 判断
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(new InnerCallBack());
application = (MyWeatherApplication) getApplication();
// 初始化控件与数据源
initTools();
// 读取偏好设置,决定显示定位
preferences = getSharedPreferences("yrcity", MODE_PRIVATE);
editor = preferences.edit();
if (preferences == null || preferences.getString("city", null) == null) {
city = "北京";
} else {
city = preferences.getString("city", null);
}
// 单击监听
ib_life.setOnClickListener(this);
ib_city.setOnClickListener(this);
new InnerThread().start();
}
/**
* 初始化控件与数据源
*/
public void initTools() {
// 控件的初始化
ll_main_container = (LinearLayout) findViewById(R.id.ll_main_container);
tv_city = (TextView) findViewById(R.id.tv_city);
tv_temperature = (TextView) findViewById(R.id.tv_temperature);
tv_weather = (TextView) findViewById(R.id.tv_weather);
tv_wind = (TextView) findViewById(R.id.tv_wind);
tv_date = (TextView) findViewById(R.id.tv_date);
tv_net = (TextView) findViewById(R.id.tv_net);
ib_life = (ImageButton) findViewById(R.id.ib_life);
ib_city = (ImageButton) findViewById(R.id.ib_city);
gv_forweather = (GridView) findViewById(R.id.gv_forweather);
// 数据的初始化
dao = new WeatherInfoDao();
}
/**
* 消息机制,加载网络上的数据
*/
private class InnerThread extends Thread {
@Override
public void run() {
try {
weather = dao.getWeatherInfo(city);
// 查询到的结果放入Application进行共享
if (weather.getCode() == 207302
|| weather.getCode() == 207301) {
editor.putString("city", "北京");
editor.commit();
city = "北京";
new InnerThread().start();
Message.obtain(handler, 0).sendToTarget();
} else if (weather.getCode() == 0
&& weather.getReason() != null) {
application.setWeather(weather);
forweathers = weather.getForweathers();
Message.obtain(handler, 1).sendToTarget();
}else {
Message.obtain(handler, 2).sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
super.run();
}
}
private class InnerCallBack implements Handler.Callback {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 0:
Toast.makeText(MainActivity.this, "查询不到该城市的信息,为您加载默认城市",
Toast.LENGTH_LONG).show();
break;
case 1:
adapter = new ForWeatherAdapter(MainActivity.this, forweathers);
gv_forweather.setAdapter(adapter);
tv_city.setText(weather.getCity_name());
tv_net.setText(weather.getLife().getWear1());
tv_temperature.setText(weather.getWeather().getTemperature()
+ "度");
tv_date.setText(weather.getDate() + " 星期" + weather.getWeek());
tv_weather.setText(weather.getWeather().getInfo());
break;
case 2:
tv_net.setText("网络连接异常");
Toast.makeText(MainActivity.this, "网络连接异常", Toast.LENGTH_LONG)
.show();
break;
}
return false;
}
}
@Override
public void onClick(View v) {
// 各个按钮的点击事件
switch (v.getId()) {
case R.id.ib_life:
Intent intent = new Intent(MainActivity.this,
LifeDetialActivity.class);
startActivity(intent);
break;
case R.id.ib_city:
Intent intent1 = new Intent(MainActivity.this, MyCityActivity.class);
startActivityForResult(intent1, 1);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 更改我的城市,及时更新界面数据
city = preferences.getString("city", null);
new InnerThread().start();
}
}
大概就是这样的吧,大家要是觉得我哪里有出错的,或者需要改动的地方可以联系我~咦,可以加我QQ哟,297514057,好吧,其实我就想看看有么有人慧眼看到这篇博客顺便加个QQ啦,啦啦啦啦啦
今天的太阳很好,一首you are my sunshine 送给你,新的一年里,记得认真的吃饭睡觉,认真的学习工作,认真的爱身边的人,包括你自己。
最后
以上就是无心小蘑菇为你收集整理的Android端天气查询(主要介绍如何利用API获取数据)的全部内容,希望文章能够帮你解决Android端天气查询(主要介绍如何利用API获取数据)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复