Android从网络上获取近三天天气

今天找了一下午的有关天气的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:



item.xml


    
    
    
    
    
    
    
    


MainActivity.java:
public class MainActivity extends Activity {

EditText et1;
TextView tv1;
ListView lv1;
ArrayList 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 getWeather(String str) throws Exception {
		ArrayList arrlist = new ArrayList();
		//获取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

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中添加

运行结果如下:

Android从网络上获取近三天天气_第1张图片

以上就是全部了。

你可能感兴趣的:(Android从网络上获取近三天天气)