Android使用"中国天气网"API数据通过城市名称获取天气情况

        项目要求在应用首页面展示本地当日天气的概况,首先想到的是google和雅虎,前者很久之前接触过,听说后来用不了了,后者由于邮箱事件的缘故个人不喜欢(虽然貌似苹果也用雅虎的天气预报),之后又想到了前段时间写的调用webservice的例子,可是频繁的在手机调用毕竟不太放心,加之免费版的各种限制,还是放弃了!搜了很多资料,也问了群里的一些人士,最后决定使用"中国天气网"来实现http://www.weather.com.cn/,在国内这个算是比较权威了吧,下面印着"中国气象局公共气象服务中心"的版权呢!通过接口返回的数据信息量很大,也比较稳定,绝对可以满足一般应用对天气的需求!就是有一点比较麻烦,需要知道对应的城市码,稍后说明我的处理办法!

        没有官方的API,都是网络上大家研究贡献的成果,普遍流传的有这么三个接口(以深圳的城市代码101280601为例):

        ①http://m.weather.com.cn/data/101280601.html 返回的信息最全的接口

{
    "weatherinfo": {
        "city": "深圳",
        "city_en": "shenzhen",
        "date_y": "2013年9月11日",
        "date": "",
        "week": "星期三",
        "fchh": "11",
        "cityid": "101280601",
        "temp1": "33℃~27℃",
        "temp2": "32℃~26℃",
        "temp3": "28℃~25℃",
        "temp4": "29℃~25℃",
        "temp5": "30℃~25℃",
        "temp6": "31℃~26℃",
        "tempF1": "91.4℉~80.6℉",
        "tempF2": "89.6℉~78.8℉",
        "tempF3": "82.4℉~77℉",
        "tempF4": "84.2℉~77℉",
        "tempF5": "86℉~77℉",
        "tempF6": "87.8℉~78.8℉",
        "weather1": "多云",
        "weather2": "阵雨",
        "weather3": "阵雨",
        "weather4": "阵雨",
        "weather5": "阵雨",
        "weather6": "阵雨",
        "img1": "1",
        "img2": "99",
        "img3": "3",
        "img4": "99",
        "img5": "3",
        "img6": "99",
        "img7": "3",
        "img8": "99",
        "img9": "3",
        "img10": "99",
        "img11": "3",
        "img12": "99",
        "img_single": "1",
        "img_title1": "多云",
        "img_title2": "多云",
        "img_title3": "阵雨",
        "img_title4": "阵雨",
        "img_title5": "阵雨",
        "img_title6": "阵雨",
        "img_title7": "阵雨",
        "img_title8": "阵雨",
        "img_title9": "阵雨",
        "img_title10": "阵雨",
        "img_title11": "阵雨",
        "img_title12": "阵雨",
        "img_title_single": "多云",
        "wind1": "微风",
        "wind2": "微风",
        "wind3": "微风",
        "wind4": "微风",
        "wind5": "微风",
        "wind6": "微风",
        "fx1": "微风",
        "fx2": "微风",
        "fl1": "小于3级",
        "fl2": "小于3级",
        "fl3": "小于3级",
        "fl4": "小于3级",
        "fl5": "小于3级",
        "fl6": "小于3级",
        "index": "炎热",
        "index_d": "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
        "index48": "炎热",
        "index48_d": "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
        "index_uv": "中等",
        "index48_uv": "中等",
        "index_xc": "不宜",
        "index_tr": "较适宜",
        "index_co": "较不舒适",
        "st1": "33",
        "st2": "26",
        "st3": "30",
        "st4": "24",
        "st5": "25",
        "st6": "23",
        "index_cl": "较适宜",
        "index_ls": "适宜",
        "index_ag": "不易发"
    }
}


         ②http://www.weather.com.cn/data/sk/101280601.html 返回的信息比较简洁

{
    "weatherinfo": {
        "city": "深圳",
        "cityid": "101280601",
        "temp": "31",
        "WD": "东南风",
        "WS": "3级",
        "SD": "58%",
        "WSE": "3",
        "time": "17:10",
        "isRadar": "1",
        "Radar": "JC_RADAR_AZ9755_JB"
    }
}

       

        ③http://www.weather.com.cn/data/cityinfo/101010100.html  另一个返回信息简洁的接口

{
    "weatherinfo": {
        "city": "深圳",
        "cityid": "101280601",
        "temp1": "26℃",
        "temp2": "32℃",
        "weather": "多云",
        "img1": "n1.gif",
        "img2": "d1.gif",
        "ptime": "18:00"
    }
}


        返回的数据是json格式的,处理起来并不麻烦,可是城市代码怎么办?一种方法是打开中国天气网的官网,在查询框中输入你所要查询的城市,浏览器跳转到的页面会显示一个地址,比如:http://www.weather.com.cn/weather/101280601.shtml,那么红色的部分就是你所查询的城市对应的城市代码!可是这也太有局限性了吧!

还有的文章介绍根据IP地址获取城市代码,但应该不适用在Android移动端吧,我没有研究,所有采用了下面的办法:第二种是将最新的城市代码放入本地数据库(数据库文件我放在末尾处,需要的可以下载,在中国范围内应该足够用了),通过在代码中查询城市名称从数据库中取出与之对应的城市代码,通过字符串的拼接发送请求,来获取想要的天气信息!这个是我自己的思路,或许比较笨拙,希望有更好想法的朋友可以指出!


下面的这段代码是根据城市名称从本地数据库中查询出与之对应的城市代码,通过封装的HttpGet方法来获取返回的数据,并使用json解析出自己所需要的内容:

public void initWaetherData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				DBHelper helper = new DBHelper(getApplicationContext());
				String cityName = "深圳";
				String cityCode = null;
				String sql = "select * from city_table where CITY =" + "'"
						+ cityName + "'" + ";";
				Log.i("TAG", "sql:" + sql);
				Cursor cursor = helper.getReadableDatabase()
						.rawQuery(sql, null);
				if (cursor != null) {
					cursor.moveToFirst();
					cityCode = cursor.getString(cursor
							.getColumnIndex("WEATHER_ID"));
					Log.i("TAG", "cityCode:" + cityCode);
				}
				cursor.close();
				helper.close();
				String weatherUrl = "http://www.weather.com.cn/data/cityinfo/" + cityCode
						+ ".html";
				String weatherJson = queryStringForGet(weatherUrl);
				Log.i("TAG", weatherJson);

				try {
					JSONObject jsonObject = new JSONObject(weatherJson);

					JSONObject weatherObject = jsonObject
							.getJSONObject("weatherinfo");

					Log.i("TAG", "city:" + weatherObject.getString("city"));
					Log.i("TAG", "temp:" + weatherObject.getString("temp1"));
					Log.i("TAG", "temp:" + weatherObject.getString("temp2"));
					Log.i("TAG","weather:" + weatherObject.getString("weather"));
					Log.i("TAG", "temp:" + weatherObject.getString("img1"));
					Log.i("TAG", "temp:" + weatherObject.getString("img2"));
					Message message = new Message();
					message.obj = weatherObject;
					handler.sendMessage(message);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}


      

在handler中根据需要将返回的内容解析并显示到界面:

private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			JSONObject object = (JSONObject) msg.obj;
			try {
				txt_weather_city.setText(object.getString("city"));
				txt_weather_temp.setText(object.getString("temp2")+"/"+object.getString("temp1"));
				txt_weather_detail.setText(object.getString("weather"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};


当然还有一个问题就是城市名字我是写死的,建议可以使用百度地图的定位功能来获取当前城市名称,然后再使用!当然还会存在很多字符串的问题,比如深圳,深圳市等等,具体问题具体分析,按照需求处理就好了!


数据库文件我放在了资源文件夹raw中了,通过读取复制到当前程序的数据库目录下,这个工具方法挺好用的(之前一个同事的工具代码),代码如下:

/** 将资源文件中的数据库文件复制到当前程序数据库目录下 */
	public void copyDatabase() {

		File file = new File(DB_PATH);
		if (!file.isDirectory())
			file.mkdir();
		String dbfile = DB_PATH + "/" + DBNAME;//自己应用数据库的名字

		try {
			if (new File(dbfile).length() == 0) {

				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];

				readDB(fos, buffer, R.raw.citychina);//数据库文件的名称

				fos.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

private void readDB(FileOutputStream fos, byte[] buffer, int db_id)
			throws IOException {
		int count;
		InputStream is;
		is = this.context.getResources().openRawResource(db_id);
		while ((count = is.read(buffer)) > 0) {
			fos.write(buffer, 0, count);
		}
		is.close();
	}


至此使用中国天气网,用城市名称获取天气状况的思路大致是这样了,只是个人的拙见,本文同样是留个备份案底,以便日后真正用起来不会抓狂!Demo和城市数据库文件的下载地址如下,数据库文件在demo的raw下面如果觉得有需要的话可以自行下载看看@_@

Demo下载地址
 


       

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
### 回答1: 要从API获取数据并在Android ListView中显示它们,可以按照以下步骤进行操作: 1. 创建一个布局文件来显示ListView。这个布局文件应该包含一个ListView组件。你可以使用XML文件来定义布局。 2. 创建一个ListView适配器。这个适配器将帮助你把数据API中加载到ListView中。 3. 在Activity或Fragment中获取数据。你可以使用Android提供的络库(如Volley、Retrofit、OkHttp等)从API获取数据。确保在获取数据时考虑到络连接的状况和错误处理。 4. 将数据绑定到适配器。在获取数据后,把它们绑定到适配器上。在这一步中,你需要将获取到的数据转换为适配器可以使用的格式。 5. 设置适配器到ListView。在绑定数据到适配器后,把适配器设置到ListView中。 下面是一个示例代码,可以用来获取数据并在ListView中显示: ```java public class MyActivity extends AppCompatActivity { private ListView listView; private List<MyDataModel> dataList; private MyDataAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_activity_layout); listView = findViewById(R.id.list_view); dataList = new ArrayList<>(); adapter = new MyDataAdapter(this, dataList); listView.setAdapter(adapter); getDataFromApi(); } private void getDataFromApi() { // 使用Volley库来获取数据 String url = "http://myapi.com/data"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> { // 成功获取数据后的处理 JSONArray jsonArray = response.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); MyDataModel data = new MyDataModel( jsonObject.getString("title"), jsonObject.getString("content") ); dataList.add(data); } adapter.notifyDataSetChanged(); }, error -> { // 获取数据失败的处理 Log.e("MyActivity", "Error while getting data from API", error); } ); Volley.newRequestQueue(this).add(request); } } ``` 在这个示例代码中,我们使用了Volley库来获取数据,然后把它们转换为MyDataModel对象,并添加到dataList中。最后,我们通过调用adapter.notifyDataSetChanged()方法来通知ListView更新数据。 ### 回答2: 在Android中,可以通过以下步骤从API获取数据并在ListView中展示: 1. 首先,确保你已经在AndroidManifest.xml文件中添加了访问络的权限。 2. 创建一个使用ListView的布局文件,并在其中添加一个ListView组件。 3. 在你的Activity类中,实例化ListView和一个自定义的ListAdapter(适配器)。 4. 使用络请求库(如Volley或Retrofit)发送一个HTTP请求到你的API,并获取返回的数据。 5. 解析服务器返回的数据,将其转换成一个列表对象。 6. 将解析后的数据传递给ListAdapter,并调用ListView的setAdapter()方法设置适配器。 7. 实现自定义的ListAdapter,并重写getView()方法以绑定数据到每个ListView的项上。 8. 最后,启动你的应用程序并应该能够从API获取数据并在ListView中显示出来。 示例代码如下: ```java // 步骤3: ListView listView = findViewById(R.id.listView); ListAdapter adapter = new ListAdapter(); listView.setAdapter(adapter); // 步骤4和5: RequestQueue queue = Volley.newRequestQueue(this); String url ="http://your-api-url.com"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 解析服务器返回的数据 List<Data> dataList = parseData(response); // 步骤6: adapter.setData(dataList); adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误 } }); queue.add(request); // 步骤7: private class ListAdapter extends BaseAdapter { private List<Data> mDataList; public void setData(List<Data> dataList) { mDataList = dataList; } @Override public int getCount() { if (mDataList == null) { return 0; } return mDataList.size(); } @Override public Data getItem(int position) { return mDataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 填充ListView的项的视图布局 // 绑定数据到视图布局中的UI组件 // 返回填充好的视图布局 } } ``` 请注意,上述代码只是简单示例,你需要根据你的具体需求和后端API的响应格式进行相应的修改和适配。 ### 回答3: 在Android中,可以通过使用络请求库(如Volley、OkHttp等)来获取API数据,并将其展示在ListView中。 首先,在AndroidManifest.xml文件中,要确保已经添加了访问络的权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 接下来,在MainActivity中,我们可以使用Volley库来进行络请求。首先,需要在`build.gradle`文件中添加Volley库的依赖: ```groovy implementation 'com.android.volley:volley:1.2.1' ``` 然后,可以在MainActivity中创建一个方法来进行络请求,获取API数据: ```java public void fetchDataFromAPI() { String url = "http://example.com/api/data"; // 替换为实际的API地址 RequestQueue queue = Volley.newRequestQueue(this); StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // 在这里解析服务器返回的JSON数据,并将其存储在一个ArrayList或其他适配器所需的数据结构中 ArrayList<String> dataList = parseDataFromResponse(response); // 实例化一个适配器,并将数据与ListView绑定 ArrayAdapter<String> adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误情况 } }); queue.add(request); } ``` 在上述代码中,首先创建一个RequestQueue对象,然后创建一个StringRequest对象,指定请求方式、url和响应监听器。在响应监听器的`onResponse`方法中,可以对服务器返回的响应数据进行解析,将其存储在合适的数据结构中,然后通过适配器将数据与ListView绑定。 最后,你可以在适当的地方调用`fetchDataFromAPI`方法来执行络请求,并在返回的数据中展示在ListView中。 这只是一种简单的从API获取数据并在ListView中展示的方法,当然也可以根据实际情况选择其他络请求库或数据解析方式来实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值