天气预报信息获取是利用json获取的,网上有非常多资源,源码。因为上面涉及到非常多天气信息,包含湿度,出行建议等,以及加入了全部城市代码的资源包。为了练手了解json的原理。我仅获取诚笃城市的最高温,最低温,城市名字。

我的布局是通过一个button获取城市名字,最高温,最低温。main.xnl代码例如以下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="城市名称:" /> <EditText
android:id="@+id/tx_cityname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText> <TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="最高温度:" /> <EditText
android:id="@+id/tx_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" /> <TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="最低温度:" /> <EditText
android:id="@+id/tx_low"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/button_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="获取实时天气信息" >
</Button>
</LinearLayout>

本project含有2个java文件各自是WheatherLck.java和WheatherInfo.java文件。WheatherLck.java代码例如以下

package com.hiden.weatherdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.JSONException;
import org.json.JSONObject; import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView; public class WeatherLck extends Activity { // 创建三个全局的文本框对象
EditText TX_CITYNAME,TX_HEIGHT,TX_LOW;
private String city_str="成都";
Button button_refresh; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // 获取布局中的文本框
TX_CITYNAME=(EditText)this.findViewById(R.id.tx_cityname);
TX_CITYNAME.setText(city_str);
TX_HEIGHT=(EditText)this.findViewById(R.id.tx_height);
TX_LOW=(EditText)this.findViewById(R.id.tx_low); button_refresh=(Button)findViewById(R.id.button_refresh); button_refresh.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==button_refresh){
refresh(city_str);
} }
}); /**************************************************************************************
* 获取http://m.weather.com.cn/data/101091106.html上面的数据
* 当中101091106为城市代码,上面我已经把城市代码做了改动,去除了空行,格式为UTF-8
* 每次仅仅是执行一次线程,然后增加主线程回收
* @param city_str
* @throws JSONException
* @throws Exception
* @throws ClientProtocolException
*/
private Thread thread;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case 1:
JSONObject weather = (JSONObject) msg.obj;
refreshUI(weather);
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
};
/************************************************************************
* 在主线程中不能请求网络
* 线程没有while循环仅仅是执行一次,假设有溢出可能不能发送消息
* @param city_str
*/
private void requestWeather(final String city_str){ thread = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub String url="http://www.weather.com.cn/data/cityinfo/101270101.html";
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
String sbuf = null;
try {
response = client.execute(httpget);
HttpEntity httpentity = response.getEntity();
if(httpentity != null){
BufferedReader br = new BufferedReader(new InputStreamReader(httpentity.getContent(),"utf-8"));
sbuf = br.readLine();
}
JSONObject object = new JSONObject(sbuf);
JSONObject data = (JSONObject) object.getJSONObject("weatherinfo");
//Log.i(TAG, data.toString());
Message msg = new Message();
msg.what = 1;
msg.obj = data;
handler.sendMessage(msg); } 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();
}
}
});
thread.start(); }
protected void refresh(String city_str)
{
requestWeather(city_str);
}
private void refreshUI(JSONObject jsonobject){ JSONObject jsonData = jsonobject;
try
{ TX_CITYNAME.setText(jsonData.getString("city"));
// 取得高温数据
TX_HEIGHT.setText(jsonData.getString("temp1"));
// 取得低温数据
TX_LOW.setText(jsonData.getString("temp2")); }catch(Exception e){
e.printStackTrace();
} } }

WheatherInfo.java代码例如以下:

package com.hiden.weatherdemo.ui;

public class WeatherInfo {
String city = "";
String temp1 = "";
String temp2 = "";// 椋庡悜 public String getCity() {
return city;
} public void setCity(String city) {
this.city = city;
} @Override
public String toString() {
return "WeatherInfo [city=" + city + ", temp1=" + temp1
+ ", temp2=" + temp2 + "]";
} public String getTemp1() {
return temp1;
} public void setTemp1(String temp) {
this.temp1 = temp;
} public String getTemp2() {
return temp2;
} public void setTemp2(String temp) {
this.temp2 = temp;
} }

点击button,获得到成都的最高温度和最低温度,效果图例如以下:

当然,大家能够依据自己的需求做出更具体的效果图,比方加入未来5天的天气,定位,加入关注城市等功能。网上资源比較多,大家能够多练习练习。

利用json获取天气信息的更多相关文章

  1. PHP Ajax JavaScript Json 实现天气信息获取

    使用第三方服务 间接方式 思路 使用到的服务 实现代码 前端完整代码 总结 要在自己的网站上添加一个天气预报功能,是一个很普通的需求,实现起来也不是很难.今天来介绍几个简单的方法. 使用第三方服务 有 ...

  2. 半吊子学习Swift--天气预报程序-获取天气信息

    昨天申请的彩云天气Api开发者今天上午已审核通过  饭后运动过后就马不停蹄的来测试接口,接口是采用经纬度的方式来获取天气信息,接口地址如下 https://api.caiyunapp.com/v2/ ...

  3. 内网公告牌获取天气信息解决方案(C# WebForm)

    需求:内网公告牌能够正确显示未来三天的天气信息 本文关键字:C#/WebForm/Web定时任务/Ajax跨域 规划: 1.天定时读取百度接口获取天气信息并存储至Txt文档: 2.示牌开启时请求Web ...

  4. java获取天气信息

    通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...

  5. Kettle通过Webservice获取天气信息

      Kettle通过Webservice获取天气信息 需求: 通过kettle工具,通过webservice获取天气信息,写成xml格式文件. 思路: Kettle可通过两种选择获取webservic ...

  6. ajax无刷新获取天气信息

    浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据,但是可以再本地的服务器上获取其他服务器的信息,在通过ajax请求本地服务来实现: <?php header("conten ...

  7. Android实现自动定位城市并获取天气信息

    定位实现代码: <span style="font-size:14px;">import java.io.IOException; import java.util.L ...

  8. ESP32 IDF 获取天气信息

    一.注册天气获取账号 我使用的知心天气,没有获取天气账号的小伙伴可以去注册一下,知心天气官网:https://www.seniverse.com/ 取得天气获取的API后,可以直接在浏览器中访问测试一 ...

  9. C#调用WebService获取天气信息

    概述 本文使用C#开发Winform应用程序,通过调用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服务WeatherWS来获取天气预 ...

随机推荐

  1. android自定义控件---添加表情

    android自定义控件---添加表情 一.定义layout文件,图片不提供了 <?xml version="1.0" encoding="utf-8"? ...

  2. Ajax技术——带进度条的文件上传

    1.概述 在实际的Web应该开发或网站开发过程中,经常需要实现文件上传的功能.在文件上传过程中,经常需要用户进行长时间的等待,为了让用户及时了解上传进度,可以在上传文件的同时,显示文件的上传进度条.运 ...

  3. VDI转vmdk(VirtualBox与VMware硬盘格式转换)[转]

    VirtualBox用了一段时间,感觉没想像中那么的好.虽然设置里可以分配多CPU,但是分配多CPU后经常系统挂掉.整体感觉不够稳定,但它也有好处就是开源免费.但经常挂机总不能一直使用它,索性转到Vm ...

  4. Hbiernate关联排序问题

    使用场景: 假设有两张表请求信息.账户表,它们之间是一对多的关系.对应的java类分别为Sfcx_RequestInfo和Sfcx_Zhxx.Sfcx_RequestInfo有一个Set属性 sfcx ...

  5. PHP 的解压缩ZipArchive中的extractTo()方法 LINUX+nginx环境中解压zip时文件丢失的问题

    在项目中要用ZipArchive解压ZIP文件,起初測试环境在WINDOWS平台中,測试通过,换到 LINUX+nginx 的环境中时 就出问题了(ZIP包中有文件和目录一共3百多个文件,大部分是带汉 ...

  6. tcp接收xml数据解析

    避免tcp接收xml数据时加上xml数据长度,根据xml数据特点来解析recv到的xml数据 int nPos1 = 0; int nPos2 = 0; int nTempPos = 0; int n ...

  7. Python写入文件,但是发现文件为空,竟然未写入!

    问题描述: fw=open(r'C:\test.txt','w') s="Hello World!" fw.write(s) ========== 此时查看C盘根目录,发现test ...

  8. swift-var/let定义变量和常量

    // Playground - noun: a place where people can play import UIKit //--------------------------------- ...

  9. 九道大型软件公司.net面试题!一定得看(附答案)

    1:a=10,b=15,在不用第三方变量的前提下,把a,b的值互换   2:已知数组int[] max={6,5,2,9,7,4,0};用快速排序算法按降序对其进行排列,并返回数组   3:请简述面向 ...

  10. [WP8] Binding时,依照DataType来选择DataTemplate

    原文 [WP8] Binding时,依照DataType来选择DataTemplate 范例下载 范例程序代码:点此下载 问题情景 在开发WPF.WP8...这类应用程序的时候,透过Binding机制 ...