android基礎學習綜合實例——天氣預報App(基本功能實現)

分類:編程 時間:2016-11-03
[摘要:3、氣象預告App根基功效完成 氣象預告首要功效便是依據鄉村的代碼,往靜態獵取當前的氣象環境,而且將當前的挑選的鄉村氣象疑息保管下去(Sharedpreferences). 1、獵取JSon]

三、天氣預報App基本功能實現
天氣預報主要功能就是根據城市的代碼,去動態獲取當前的天氣情況,並且將當前的選擇的城市天氣信息保存下來(Sharedpreferences).
1、獲取JSon天氣數據
2、根據android基礎學習綜合實例——天氣預報App中分析的城市代碼以及天氣代碼,保存到數據庫中,再根據用戶所選擇的城市代碼,獲取對應的天氣信息
3、特別註意,因為白天已經過去 ,預報在晚上那次更新的時候白天數據就會為空,即中國氣象局的數據在晚上6點以後不會再更新白天的數據信息,在App中必須保存白天的天氣信息。

3.1 城市代碼數據庫建立
(1)省份Province代碼數據庫:包括省份名稱和代碼

private static final String CREATE_PROVINCE = "create table Province ("
            + "id integer primary key autoincrement, " 
            + "province_name text, "
            + "province_code text)";

添加對應的數據庫操作
1)保存省份實例到數據庫中

public void saveProvince(Province province)
{
    if (province != null)
    {
        ContentValues values = new ContentValues();
        values.put("province_name", province.getProvinceName());
        values.put("province_code", province.getProvinceCode());
        db.insert("Province", null, values);
    }
}

2.在數據庫中讀取全國的所有省份

public List<Province> loadProvices()
{

    List<Province> list = new ArrayList<Province>();
    Cursor cursor = db
    .query("Province", null, null, null, null, null, null);
    if (cursor.moveToFirst())
    {
        do
        {
            Province province = new Province();        province.setId(cursor.getInt(cursor.getColumnIndex("id")));
province.setProvinceName(cursor.getString(cursor
                    .getColumnIndex("province_name")));
            province.setProvinceCode(cursor.getString(cursor
                    .getColumnIndex("province_code")));
            list.add(province);
        } while (cursor.moveToNext());
    }
    return list;
}

(2)市級City代碼數據庫表建立

private static final String CREATE_CITY = "create table City ("
            + "id integer primary key autoincrement, "
            + "city_name text, "
            + "city_code text, "
            + "province_id integer)";

1.保存City信息到數據庫中

public void saveCity(City city)
{
    if (city != null)
    {
        ContentValues values = new ContentValues();
        values.put("city_name", city.getCityName());
        values.put("city_code", city.getCityCode());
        values.put("province_id", city.getProvinceId());
        db.insert("City", null, values);
    }
}

2.根據用戶所選的省份id,在數據庫中讀取對應的市級城市數據

public List<City> loadCity(int provinceId)
{
    List<City> list = new ArrayList<>();
    Cursor cursor = db.query("City", null, "province_id = ?", new String[]
    { String.valueOf(provinceId) }, null, null, null);
    if (cursor.moveToFirst())
    {
        do
        {
            City city = new City();
            city.setId(cursor.getInt(cursor.getColumnIndex("id")));
            city.setCityName(cursor.getString(cursor
                    .getColumnIndex("city_name")));
            city.setCityCode(cursor.getString(cursor
                    .getColumnIndex("city_code")));
            city.setProvinceId(provinceId);
            list.add(city);
        } while (cursor.moveToNext());

    }
    return list;
}

(3)縣級County城市代碼數據庫建立

private static final String CREATE_COUNTY = "create table County ("
            + "id integer primary key autoincrement, "
            + "county_name text, "
            + "county_code text, "
            + "city_id integer)";

1.保存County信息到數據庫中

public void saveCounty(County county)
{
    if (county != null)
    {
        ContentValues values = new ContentValues();
        values.put("county_name", county.getCountyName());
        values.put("county_code", county.getCountyCode());
        values.put("city_id", county.getCityId());
        db.insert("County", null, values);
    }

}

2.根據City的id在數據中獲取對應的縣城數據

public List<County> loadCounties(int cityId)
{
    List<County> list = new ArrayList<County>();
    Cursor cursor = db.query("County", null, "city_id = ?", new String[]
    { String.valueOf(cityId) }, null, null, null);
    if (cursor.moveToFirst())
    {
        do
        {
            County county = new County();
            county.setCityId(cursor.getInt(cursor.getColumnIndex("id")));
            county.setCountyName(cursor.getString(cursor
                    .getColumnIndex("county_name")));
            county.setCountyCode(cursor.getString(cursor
                    .getColumnIndex("county_code")));
            county.setCityId(cityId);
            list.add(county);

        } while (cursor.moveToNext());
    }
    return list;
}

3.2 根據城市代碼在線獲取城市的天氣信息
因為中國氣象局返回的數據是JSon格式的,所以我們通過解析JSon格式的數據,獲得對應的天氣信息。

(1)根據城市代碼在線獲取天氣JSon數據

public static void sendHttpRequest(final String address,
            final HttpCallbackListener listener)
{
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            HttpURLConnection connection = null;
            URL url;
            try
            {
                url = new URL(address);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                InputStream in = connection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in,"UTF-8"));//這裏用UTF-8是為了防止獲取得到的JSON數據中出現中文而導致亂碼
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null)
                {
                    response.append(line);
                }
                if (listener != null)
                {
                    // 回調onFinish()方法
                listener.onFinish(response.toString());
                }
                in.close();
            } catch (Exception e)
            {
                if (listener != null) {
                    // 回調onError()方法
                    listener.onError(e);
                }
            } finally{
                if(connection != null){
                    connection.disconnect();
                }
            }

        }
    }).start();

}

其中listener是自定義的一個回調接口,通過回調接口可方便獲得返回的天氣信息response

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

以上都是基本準備工作,本APP中主要包括2個Activity:ChooseAreaAcitvity和WeatherActivity。
3.3 ChooseAreaActivity:通過讀取Excel獲取城市的代碼以及名稱並顯示

public static String loadProvincesInfo(Context context,String xlsPath) throws IOException
{
    if(xlsPath.equals("Area_Excel")){
        StringBuilder provinceInfo= new StringBuilder();
        try{

            InputStream is = context.getAssets().open("areaid_v.xls");
            //ileInputStream fileIn = new FileInputStream(xlsPath);
            // 根據指定的文件輸入流導入Excel從而產生Workbook對象
            HSSFWorkbook wb0 = new HSSFWorkbook(is);
            // 獲取Excel文檔中的第一個表單
            HSSFSheet hssfSheet = wb0.getSheetAt(0);
            // 對Sheet中的每一行進行叠代
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++)
            {

                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                // 如果當前行的行號(從0開始)未達到2(第三行)則從新循環
                if (hssfRow != null)
                {
                    // 創建實體類
                    HSSFCell no = hssfRow.getCell(0);
                    HSSFCell proname = hssfRow.getCell(6);
                    HSSFCell cityname = hssfRow.getCell(4);
                    HSSFCell countyname = hssfRow.getCell(2);
                    /*
                     * String subNo = getValue(no).substring(3, 5);//[3,5)
                     */
                    //返回一行中的省市縣的名稱已經整個Number 
                    String info = getValue(no) + "|" + getValue(proname) + "|"
                            + getValue(cityname) + "|" + getValue(countyname) + ",";
                    provinceInfo.append(info);
                }
            }
            /*fileIn.close();*/
            is.close();
            return provinceInfo.toString();

        }catch(Exception e){
            Log.d("TAG", "加載excel文件出錯");
        }
        return provinceInfo.toString();
    }else{
        Log.d("TAG", "加載excel類型出錯,應該為地區類型");
        return null;
    }

}

Tags:

文章來源:


ads
ads

相關文章
ads

相關文章

ad