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

本文介绍如何使用心知天气API获取并展示天气信息,通过一个详细的demo,包括注册获取API密钥、网络请求、JSON解析及UI展示,帮助读者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

运行结果如下:

在这里插入图片描述

以上就是全部了。

Android天气预报实验报告模板 public class SetCityActivity extends Activity { //定义的一个自动定位的列表 private ListView gpsView; //定义的一个省份可伸缩性的列表 private ExpandableListView provinceList; //定义的用于过滤的文本输入框 private TextView filterText; //定义的一个记录城市码的SharedPreferences文件名 public static final String CITY_CODE_FILE="city_code"; //城市的编码 private String[][] cityCodes; //省份 private String[] groups; //对应的城市 private String[][] childs; //自定义的伸缩列表适配器 private MyListAdapter adapter; //记录应用程序widget的ID private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set_city); gpsView = (ListView)findViewById(R.id.gps_view); provinceList= (ExpandableListView)findViewById(R.id.provinceList); //设置自动定位的适配器 gpsView.setAdapter(new GPSListAdapter(SetCityActivity.this)); //==============================GPS================================= //当单击自动定位时 gpsView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView localeCity = (TextView)view.findViewById(R.id.locateCityText); localeCity.setText("正在定位..."); final LocateHandler handler = new LocateHandler(localeCity); //添加一个线程来处理定位 new Thread(){ public void run() { Map<Integer, String> cityMap= getLocationCityInfo(); //记录匹配的城市的索引 int provinceIndex = -1; int cityIndex = -1; //传给处理类的数据封装对象 Bundle bundle = new Bundle(); if(cityMap!=null) { //得到图家名 String country = cityMap.get(LocationXMLParser.COUNTRYNAME); //只匹配中国地区的天气 if(country!=null&&country.equals("中国")){ //得到省 String province = cityMap.get(LocationXMLParser.ADMINISTRATIVEAREANAME); //得到市 String city = cityMap.get(LocationXMLParser.LOCALITYNAME); //得到区县 String towns = cityMap.get(LocationXMLParser.DEPENDENTLOCALITYNAME); Log.i("GPS", "============"+province+"."+city+"."+towns+"=============="); //将GPS定位的城市与提供能查天气的城市进行匹配 StringBuilder matchCity = new StringBuilder(city); matchCity.append("."); matchCity.append(towns); //找到省份 for(int i=0; i<groups.length; i++) { if(groups[i].equals(province)) { provinceIndex = i; break; } }
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值