今天找了一下午的有关天气的api,写了一个获取天气的小demo,希望能够帮到有需要的朋友。
首先,需要找到一些开放的api,这里以心知天气https://www.seniverse.com为例,给大家作详细介绍。更多请访问https://www.jianshu.com/p/e3e04cf3fc0f。
1.在心知天气里注册一下,然后可以获得 API密钥 .
2. 单开一个线程访问网络。网站地址https://api.seniverse.com/v3/weather/daily.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&days=5.
注意:your_api_key是你的 API密钥 。 location = 城市的拼音。例如上面的beiijing
3.解析获取的数据。获取的数据是以json形式返回的。
4.将解析好的数据以listview的形式显示在activity上。
详细代码如下:
activity_main.xml:
<EditText
android:id="@+id/city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入城市拼音" />
<Button
android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/city"
android:text="查询"
android:onClick="click" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/bt1"
android:textSize="15sp"/>
<ListView
android:id="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/tv1">
</ListView>
item.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:orientation="horizontal" >
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="date"
android:textColor="#000" />
<TextView
android:id="@+id/text_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/date"
android:layout_marginLeft="5dp"
android:text="text_day"
android:textColor="#000" />
<TextView
android:id="@+id/text_night"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/text_day"
android:layout_marginLeft="5dp"
android:text="text_night"
android:textColor="#000" />
<TextView
android:id="@+id/low"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text_day"
android:layout_alignLeft="@id/text_day"
android:text="low"
android:textColor="#000" />
<TextView
android:id="@+id/high"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text_day"
android:layout_toRightOf="@id/low"
android:layout_marginLeft="5dp"
android:text="high"
android:textColor="#000" />
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
EditText et1;
TextView tv1;
ListView lv1;
ArrayList<Weather> arrlist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.city);
tv1 = (TextView) findViewById(R.id.tv1);
lv1 = (ListView) findViewById(R.id.lv1);
}
public void click(View v) {
if(v.getId()==R.id.bt1) {
new Thread(){
@Override
public void run() {
try {
String city = et1.getText().toString().trim();
String path = "https://api.seniverse.com/v3/weather/daily.json?key=l57oxruu6tlsxnw4&location="+city+
"&language=zh-Hans&unit=c&start=0&days=5";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200) {
//请求成功
InputStream in = conn.getInputStream();
String str = "";
int len=0;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0) {
str += new String(buffer,0,len);
}
//解析json
arrlist = MyJsonParser.getWeather(str);
runOnUiThread(
new Runnable() {
public void run() {
tv1.setText(arrlist.get(0).getCity());
lv1.setAdapter(new MyAdapter());
}
}
);
}else {
showContent("请求失败");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
showContent("服务器繁忙。。。");
}
}
}.start();
}
}
public void showContent(final String str) {
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
return arrlist.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View vertview, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
if(vertview==null) {
//使用打气筒找到item
view = View.inflate(getApplicationContext(), R.layout.item, null);
}else {
view = vertview;
}
// 找到相关的控件
TextView date = (TextView) view.findViewById(R.id.date);
TextView text_day = (TextView) view.findViewById(R.id.text_day);
TextView text_night = (TextView) view.findViewById(R.id.text_night);
TextView low = (TextView) view.findViewById(R.id.low);
TextView high = (TextView) view.findViewById(R.id.high);
//设置相关的值
Weather wea = arrlist.get(position);
date.setText(wea.getDate());
text_day.setText("白天:"+wea.getText_day());
text_night.setText("晚上:"+wea.getText_night());
low.setText("最低温度:"+wea.getLow());
high.setText("最高温度"+wea.getHigh());
return view;
}
}
}
解析工具类
MyJsonParser.java:
public class MyJsonParser {
public static ArrayList<Weather> getWeather(String str) throws Exception {
ArrayList<Weather> arrlist = new ArrayList<Weather>();
//获取json对象
JSONObject json = new JSONObject(str);
JSONArray results = json.getJSONArray("results");
//获取城市
JSONObject location = (JSONObject) results.get(0);
String city = location.getJSONObject("location").getString("name");
//获取daily数组
JSONArray daily = location.getJSONArray("daily");
for(int i=0;i<daily.length();i++) {
//准备一个weather对象
Weather weather = new Weather();
//添加城市
weather.setCity(city);
JSONObject day = (JSONObject) daily.get(i);
//获取日期
String date = day.getString("date");
weather.setDate(date);
//获取text_day(白天天描述)
String text_day = day.getString("text_day");
weather.setText_day(text_day);
//获取text_night(夜晚天描述)
String text_night = day.getString("text_night");
weather.setText_night(text_night);
//获取最高温度
String high = day.getString("high");
weather.setHigh(high);
//获取最低温度
String low = day.getString("low");
weather.setLow(low);
arrlist.add(weather);
}
return arrlist;
}
}
weather类
Weather.java:
public class Weather {
private String city; //城市
private String date; //日期
private String text_day; //白天天气描述
private String text_night; //夜晚天气描述
private String high; // 最高温度
private String low; //最低温度
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getText_day() {
return text_day;
}
public void setText_day(String text_day) {
this.text_day = text_day;
}
public String getText_night() {
return text_night;
}
public void setText_night(String text_night) {
this.text_night = text_night;
}
public String getHigh() {
return high;
}
public void setHigh(String high) {
this.high = high;
}
public String getLow() {
return low;
}
public void setLow(String low) {
this.low = low;
}
@Override
public String toString() {
return "Weather [city=" + city + ", date=" + date + ", text_day="
+ text_day + ", text_night=" + text_night + ", high=" + high
+ ", low=" + low + "]";
}
}
最后,千万别忘了添加网络权限。
在AndroidManifest.xml中添加
运行结果如下:
以上就是全部了。