第一行代码酷欧天气开发(二)

在这一阶段,我们的目标是遍历全国省市县数据,我们从前面的介绍中已经看出,我们可以从服务器端得到我们想要的数据,因此在这里和服务器的交互是少不了的了,所以我们现在util包下增加一个HttpUtil类

package com.coolweather.app.util;

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

import android.util.Log;

public class HttpUtil {
    public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
        new Thread(new Runnable() {

            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null)
                        response.append(line);
                    Log.d("HttpUtil",response+"");
                    if(listener != null)
                        listener.onFinish(response.toString());
                    } catch (Exception e) {
                        if(listener != null)
                        listener.onError(e);                
                        }finally{
                            if(connection != null)
                            connection.disconnect();
                        }

            }
        }).start();
    }


}

HttpUtil中使用到了HttpCallbackListener接口来回掉服务返回的结果,因此我们还需要在util包下添加这个接口

package com.coolweather.app.util;

public interface HttpCallbackListener {
    void onFinish(String response);
    void onError(Exception e);

}

另外,由于服务器返回的省市县数据都是“代号|城市,代号|城市”这种格式的,所以我们最好再提供一个工具类来解析和处理这种数据,再util包下新建一个Utility类

package com.coolweather.app.util;

import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;

/**
 * xml格式进行解析和处理
 * @author aiyuan
 * @time 2016.9.8
 *
 */

public class Utility {
    static String TAG = "Utility";
    /**
     * 解析和处理服务器返回的省级数据
     * @param coolWeatherDB
     * @param response
     * @return
     */
    public synchronized static boolean handleProvincesResponse(CoolWeatherDB coolWeatherDB,String response){
        if(!TextUtils.isEmpty(response)){
            Log.d("utility response", response);
            String[] allProvinces = response.split(",");
            if(allProvinces != null && allProvinces.length > 0){
                for(String p : allProvinces){
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvinceCode(array[0]);
                    province.setProvinceName(array[1]);
                    //将解析出来的数据存储到Province表
                    coolWeatherDB.saveProvince(province);
                }
                return true;
            }
        }
        return false;
    }
    /**
     * 解析和处理服务器返回的市级数据
     * @param coolWeatherDB
     * @param response
     * @param provinceId
     * @return
     */
    public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,String response,int provinceId){
        if(!TextUtils.isEmpty(response)){
            Log.d("utility response", response);
            String[] allCities = response.split(",");
            if(allCities != null && allCities.length > 0){
                for(String c : allCities){
                    String[] array = c.split("\\|");
                    City city = new City();
                    city.setCityCode(array[0]);
                    city.setCityName(array[1]);
                    city.setProvinceId(provinceId);
                    //将解析出来的数据存储到City表
                    coolWeatherDB.saveCity(city);
                }
                return true;
            }
        }
        return false;
    }
    /**
     * 解析和处理服务器返回的县级数据
     * @param coolWeatherDB
     * @param response
     * @param cityId
     * @return
     */
    public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,String response,int cityId){
        if(!TextUtils.isEmpty(response)){
            Log.d("utility response", response);
            String[] allCounties = response.split(",");
            if(allCounties != null && allCounties.length > 0){
                for(String c : allCounties){
                    String[] array = c.split("\\|");
                    County county = new County();
                    county.setCountyCode(array[0]);
                    Log.d(TAG, array[0]);
                    county.setCountyName(array[1]);
                    county.setCityId(cityId);
                    //将解析出来的数据存储到county表
                    coolWeatherDB.saveCounty(county);
                }
                return true;
            }
        }
        return false;
    }

}

这个类里的三个方法,分别用于解析和处理服务器返回的省级,市级,县级数据,解析的规则就是先按逗号分隔,再按单竖线分隔,接着将解析出来的数据设置到实体类中,最后调用CoolWeatherDB中的三个save()方法将数据存储到相应的表中。
这里写图片描述

现在我们开始写界面,再res/layout目录中新建choose_area.xml布局

<?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" >

    <RelativeLayout 
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#484E61">
        <TextView 
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#fff"
            android:textSize="24sp"/>
    </RelativeLayout>

    <ListView 
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>


</LinearLayout>

布局内容比较简单,listview用于显示省市县的数据
下面也就是最关键的一步了,遍历省市县数据的活动了,再activity包下新建ChooseAreaActivity继承自Activity,由于ChooseAreaActivity里面代码蛮多,截图上要讲解的蛮多,就新开一个blog,点下面

第一行代码酷欧天气开发(三)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值