«

Android实战--天气预报(API+JSON解析)

时间:2024-3-2 17:12     作者:韩俊     分类: Android


学习安卓有一段时间了,应该提高自己的实战能力,做一些简单的Demo。下面我们介绍一下如何利用网络API实现天气预报功能,主要涉及到如何利用API获得网络数据,网络数据返回一般是JSON格式,这里又涉及到JSON的解析问题,这些都是比较基础的问题,应该予以掌握。

首先在http://apistore.baidu.com/?qq-pf-to=pcqq.c2c找到你想要的API,这里我们选择http://apistore.baidu.com/astore/serviceinfo/1798.html,网页里有关于API的介绍:

接口地址:http://apistore.baidu.com/microservice/weather

请求方法:GET

请求参数:

参数名

类型

必填

参数位置

描述

默认值

citypinyin

string

urlParam

城市拼音

beijing

请求示例:

http://apistore.baidu.com/microservice/weather?citypinyin=beijing

JSON返回示例:

{
errNum: 0,
errMsg: "success",
retData: {
   city: "北京", //城市
   pinyin: "beijing", //城市拼音
   citycode: "101010100",  //城市编码 
   date: "15-02-11", //日期
   time: "11:00", //发布时间
   postCode: "100000", //邮编
   longitude: 116.391, //经度
   latitude: 39.904, //维度
   altitude: "33", //海拔   
   weather: "晴",  //天气情况
   temp: "10", //气温
   l_tmp: "-4", //最低气温
   h_tmp: "10", //最高气温
   WD: "无持续风向",    //风向
   WS: "微风(<10m/h)", //风力
   sunrise: "07:12", //日出时间
   sunset: "17:44" //日落时间
  }    
}

下面搞一下布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:text="天气预报"
        android:textSize="26dp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/myedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1111" />

        <Button
            android:id="@+id/searchweather"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="查询天气 " />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="城市:" />

        <TextView
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="天气:" />

        <TextView
            android:id="@+id/weather"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="实时气温:" />

        <TextView
            android:id="@+id/temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="最低气温:" />

        <TextView
            android:id="@+id/h_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="最高气温:" />

        <TextView
            android:id="@+id/l_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>


下面连接工具类:

package org.lxh.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloader {

    private URL url = null;

    /**
     * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容 1.创建一个URL对象
     * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStream 4.从InputStream当中读取数据
     * 
     * @param urlStr
     * @return
     */
    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url
                    .openConnection();
            urlConn.setRequestMethod("GET");
            urlConn.setConnectTimeout(8000);
            urlConn.setReadTimeout(8000);
            buffer = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}


获取返回字符串之后要对此JSON数据进行解析:

package org.lxh.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

public class Util {

    public List<Map<String, Object>> getInformation(String jonString)
            throws Exception {

        JSONObject jsonObject = new JSONObject(jonString);
        JSONObject retData = jsonObject.getJSONObject("retData");
        List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cityName", retData.optString("city"));
        map.put("weather", retData.optString("weather"));
        map.put("temp", retData.optString("temp"));
        map.put("l_temp", retData.optString("l_tmp"));
        map.put("h_temp", retData.optString("h_tmp"));
        all.add(map);

        return all;

    }

}


下面Activity程序:

package org.lxh.demo;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity {
    private EditText citynameEditText;
    private Button searchWeatherButton;
    private TextView citynametTextView;
    private TextView weahterTextView;
    private TextView tempTextView;
    private TextView h_tempTextView;
    private TextView l_tempTextView;
    String jonString;
    ProgressDialog progressDialog;
    private static final int SET = 1;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SET:
                Util util = new Util();
                try {
                    List<Map<String, Object>> all = util
                            .getInformation(msg.obj.toString());
                    Iterator<Map<String, Object>> iterator = all.iterator();
                    while (iterator.hasNext()) {
                        Map<String, Object> map = iterator.next();
                        Log.d("天气", map.get("weather").toString());
                        citynametTextView.setText(map.get("cityName")
                                .toString());
                        weahterTextView.setText(map.get("weather").toString());
                        tempTextView.setText(map.get("temp").toString());
                        h_tempTextView.setText(map.get("l_temp").toString());
                        l_tempTextView.setText(map.get("h_temp").toString());

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
                break;

            }

        }

    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // 生命周期方法
        super.setContentView(R.layout.main); // 设置要使用的布局管理器
        citynameEditText = (EditText) findViewById(R.id.myedit);
        searchWeatherButton = (Button) findViewById(R.id.searchweather);
        citynametTextView = (TextView) findViewById(R.id.city);
        weahterTextView = (TextView) findViewById(R.id.weather);
        tempTextView = (TextView) findViewById(R.id.temp);
        h_tempTextView = (TextView) findViewById(R.id.h_temp);
        l_tempTextView = (TextView) findViewById(R.id.l_temp);

        searchWeatherButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                new Thread(new NewThread()).start();
                Log.d("按键", "Success");

            }
        });
    }

    private class NewThread implements Runnable {

        public void run() {

            String address = "http://apistore.baidu.com/microservice/weather?citypinyin="
                    + citynameEditText.getText().toString();

            HttpDownloader httpDownloader = new HttpDownloader();
            String jonString = httpDownloader.download(address);
            Message msg = Main.this.handler
                    .obtainMessage(Main.SET, jonString);
            Main.this.handler.sendMessage(msg);

        }

    }

}


运行实例效果:

DEMO下载地址:http://download.csdn.net/detail/yayun0516/8705675

本例子只解析了几个数据作为例子,如有需要其他数据,可以自行添加,原理相同。发挥你的想象吧!

最后:

我的应用: http://openbox.mobilem.360.cn/index/d/sid/2966005

http://android.myapp.com/myapp/detail.htm?apkName=com.yayun.gitlearning

欢迎下载,有问题多交流!

标签: android

热门推荐