Android导入外部数据库解析json获取天气预报


Android导入外部数据库解析json获取天气预报


运行界面:



1.修改了下之前的代码,不用导入数据库到/data/data/包名 文件夹下,直接放在/res/raw文件夹不会被二进制压缩


[java]  view plain copy
  1. public static SQLiteDatabase openDatabase(Context context) {  
  2.         try {  
  3.             // Context context=new TestActivity();  
  4.             String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;  
  5.             File dir = new File(DATABASE_PATH);  
  6.             if (!dir.exists()) // 如果文件夹不存在创建文件夹  
  7.             {  
  8.                 dir.mkdir();  
  9.                 System.out.println("File build success");  
  10.             }  
  11.             if (!(new File(databaseFilename)).exists()) { // 如果文件不存在创建文件  
  12.                 InputStream is = context.getResources().openRawResource(  
  13.                         R.raw.chinacity);  
  14.                 FileOutputStream fos = new FileOutputStream(databaseFilename);  
  15.                 byte[] buffer = new byte[8192];  
  16.                 int count = 0;  
  17.                 while ((count = is.read(buffer)) > 0) {  
  18.                     fos.write(buffer, 0, count);  
  19.                 }  
  20.                 fos.close();  
  21.                 is.close();  
  22.             }  
  23.             db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);  
  24.   
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.         if (db != null) {  
  29.             System.out.println("db build success!");  
  30.         } else {  
  31.             System.out.println("db build failed!");  
  32.         }  
  33.         return db;  
  34.     }  

得到数据库:


[java]  view plain copy
  1. JSON mJson = new JSON(MainActivity.this);  

[java]  view plain copy
  1. db = DBUtils.openDatabase(mContext);  

2.连接网络:

[java]  view plain copy
  1. private static String getConnection(String path)  
  2.             throws MalformedURLException, IOException, ProtocolException {  
  3.         URL url = new URL(path);  
  4.         try {  
  5.             HttpURLConnection cn = (HttpURLConnection) url.openConnection();  
  6.             cn.setConnectTimeout(5 * 1000);  
  7.             cn.setRequestMethod("GET");  
  8.             // System.out.println("stream=======" + cn.getInputStream());  
  9.             InputStreamReader in = new InputStreamReader(cn.getInputStream());  
  10.             // System.out.println("in======" + in);  
  11.   
  12.             // 流的应用与读取  
  13.             BufferedReader bu = new BufferedReader(in);  
  14.             String line = bu.readLine().toString();  
  15.             System.out.println("流数据line========" + line);  
  16.             bu.close();  
  17.             in.close();  
  18.             return line;  
  19.         } catch (Exception e) {  
  20.             // TODO Auto-generated catch block  
  21.             e.printStackTrace();  
  22.             System.out.println("查询失败,请检查网络...");  
  23.             return null;  
  24.         }  
  25.     }  

注:这里我试过所有华为手机都连接不了,其他的htl,中兴都可以,不知道什么原因


3.json获取数据,通过中央气象台的apt访问


使用http://www.weather.com.cn/data/sk/101010100.html获取当日天气的信息,打开网址可以看到文本信息如下(已经格式化过):

 

{"weatherinfo":

{"city":"北京”,

"cityid":"101010100”,

"temp":"-1”,

"WD":"北风”,

"WS":"3级”,

"SD":"18%”,

"WSE":"3”,

"time":"15:10”,

"isRadar":"1”,

"Radar":"JC_RADAR_AZ9010_JB"}

}

这是一个JSON数据格式信息,接下来会通过解析来获取其中信息,我们需要的字段如下表1.1.1 1所示:

 

字段名称

代码含义

city

城市名称

cityid

城市id

temp

实时温度

WD

风向

WS

风级数

SD

湿度

time

天气预报发布时间

 

表1.1.1‑1    关键字段及其含义1

 

其中最关键的字段是cityid,解析天气将会使用这个字段作为唯一标识符,同样使用api:http://m.weather.com.cn/data/101010100.html获取未来五天的天气情况及其图标,打开连接地址得到如下文本(已经格式化):

 

{"weatherinfo":

{"city":"北京”,

"city_en":"beijing”,

"date_y":"2013年1月8日”,

"date":"“,

"week":"星期二”,

"fchh":"11”,

"cityid":"101010100”,

"temp1":"0℃~-11℃”,

"temp2":"0℃~-10℃”,

"temp3":"0℃~-7℃”,

"temp4":"2℃~-7℃”,

"temp5":"1℃~-6℃”,

"temp6":"0℃~-6℃”,

"tempF1":"32℉~12.2℉”,

"tempF2":"32℉~14℉”,

"tempF3":"32℉~19.4℉”,

"tempF4":"35.6℉~19.4℉”,

"tempF5":"33.8℉~21.2℉”,

"tempF6":"32℉~21.2℉”,

"weather1":"晴”,

"weather2":"晴”,

"weather3":"多云转阴”,

"weather4":"多云转晴”,

"weather5":"晴转多云”,

"weather6":"多云转晴”,

"img1":"0”,

"img2":"99”,

"img3":"0”,

"img4":"99”,

"img5":"1”,

"img6":"2”,

"img7":"1”,

"img8":"0”,

"img9":"0”,

"img10":"1”,

"img11":"1”,

"img12":"0”,

"img_single":"0”,

"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":"天气寒冷,建议着厚羽绒服、毛皮大衣加厚毛衣等隆冬服装。年老体弱者尤其要注意保暖防冻。”,

"index48":"寒冷”,

"index48_d":"天气寒冷,建议着厚羽绒服、毛皮大衣加厚毛衣等隆冬服装。年老体弱者尤其要注意保暖防冻。”,

"index_uv":"弱”,

"index48_uv":"弱”,

"index_xc":"适宜”,

"index_tr":"较适宜”,

"index_co":"较不舒适”,

"st1":"0”,

"st2":"-10”,

"st3":"0”,

"st4":"-7”,

"st5":"0”,

"st6":"-7”,

"index_cl":"适宜”,

"index_ls":"基本适宜”,

"index_ag":"极不易发"}

}

 

其中用到的关键字段如下表1.1.1-2:

 

字段名称

代码含义

city

城市名称

cityid

城市id

day_y

当前时间

temp1

今天温度最低温和最高温

temp2

明天温度最低温和最高温

temp3

第三天温度最低温和最高温

temp4

第四天度最低温和最高温

temp5

第五天度最低温和最高温

temp6

第六天度最低温和最高温

weather1

今天天气描述

img1

今天白天温度图标

img3

明天白天温度图标

img5

第三天白天温度图标

img7

第四天白天温度图标

img9

第五天白天温度图标

img11

第六天白天温度图标

 

表1.1.1‑2    关键字段及对应含义2

 

注意其中温度坐标字段(img1, img3, img5, img7, img9, img11)只是给出了图标的编号,需要拼接字符串来获取网络图片,比如得到img1,则图片地址为 http://m.weather.com.cn/img/b1.gif这个就是今天白天温度图标的图片网址,其中”b1.gif”就是图片的名字和样式,”b”表示这个图标是50*46像素,”1”就是”img”中的”1”,不同数字表示不同图标,获取图标后就可以通过Bitmap类型显示出来

代码:


[java]  view plain copy
  1. public static List<Map<String, String>> getTodayWeather(String path) {  
  2.   
  3.     List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
  4.     String json = null;  
  5.     Map<String, String> map;  
  6.   
  7.     try {  
  8.         String line = getConnection(path);  
  9.         // 字符数组转换成字符串  
  10.   
  11.         if (line != null) {  
  12.             json = new String(line);  
  13.             // 这里是以对象的形式  
  14.             JSONObject item1 = new JSONObject(json);  
  15.             // 得到对象中的对象  
  16.             JSONObject item = item1.getJSONObject("weatherinfo");  
  17.   
  18.             // 城市名字,阴天,3-4°,北风三级,湿度,日期  
  19.             String city = item.getString("city");  
  20.             String temp = item.getString("temp");  
  21.             String wind = item.getString("WD") + item.getString("WS");  
  22.             String wet = item.getString("SD");  
  23.             String time = item.getString("time");  
  24.   
  25.             // 添加到MAP中  
  26.   
  27.             map = new HashMap<String, String>();  
  28.   
  29.             map.put("city", city);  
  30.             map.put("temp", temp);  
  31.             map.put("wind", wind);  
  32.             map.put("wet", wet);  
  33.             map.put("time", time);  
  34.             list.add(map);  
  35.         } else {  
  36.             System.out.println("获取留数据失败!");  
  37.         }  
  38.   
  39.     } catch (MalformedURLException e) {  
  40.         // TODO Auto-generated catch block  
  41.         e.printStackTrace();  
  42.     } catch (ProtocolException e) {  
  43.         // TODO Auto-generated catch block  
  44.         e.printStackTrace();  
  45.     } catch (IOException e) {  
  46.         // TODO Auto-generated catch block  
  47.         e.printStackTrace();  
  48.     } catch (JSONException e) {  
  49.         // TODO Auto-generated catch block  
  50.         e.printStackTrace();  
  51.     }  
  52.     return list;  
  53. }  

源代码:

http://pan.baidu.com/share/link?shareid=186137&uk=3875834366


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
天气查询APP,两种JSON解析方式 /** * 原始json数据解析 * */ // JSONObject jsonObject = new JSONObject(res); // String reason=jsonObject.getString("reason"); // if (reason.equals("参数不正确")){ // handler.sendEmptyMessage(1); // return; // } // JSONObject result=jsonObject.getJSONObject("result"); // JSONObject realtime=result.getJSONObject("realtime"); // JSONObject life=result.getJSONObject("life"); // JSONObject wind=realtime.getJSONObject("wind"); // String time=realtime.getString("time"); // JSONObject weather=realtime.getJSONObject("weather"); // String date=realtime.getString("date"); // dateStr=time+date; // weekStr=realtime.getString("week"); // calendarStr=realtime.getString("moon"); // windpowerStr=wind.getString("direct")+" "+wind.getString("power"); // weatherStr=weather.getString("info"); // temperatureStr=weather.getString("temperature"); // JSONObject info=life.getJSONObject("info"); // JSONArray kongtiao=info.getJSONArray("kongtiao"); // JSONArray yundong=info.getJSONArray("yundong"); // JSONArray ziwaixian=info.getJSONArray("ziwaixian"); // ACStr=kongtiao.getString(0)+" "+kongtiao.getString(1); // sportStr=yundong.getString(0)+" "+yundong.getString(1); // lightStr=ziwaixian.getString(0)+" "+ziwaixian.getString(1); /** * Gson数据解析 */ WheatherBean wheatherBean=new Gson().fromJson(res,WheatherBean.class); String reason=wheatherBean.getReason(); if (reason.equals("参数不正确")){ handler.sendEmptyMessage(1); return; } WheatherBean.ResultBean resultBean=wheatherBean.getResult(); WheatherBean.ResultBean.RealtimeBean realtimeBean=resultBean.getRealtime(); WheatherBean.ResultBean.RealtimeBean.WindBean windBean=realtimeBean.getWind(); String time=realtimeBean.getTime(); WheatherBean.ResultBean.RealtimeBean.WeatherBean weatherBean=realtimeBean.getWeather(); String date=realtimeBean.getDate(); dateStr=time+date; weekStr=realtimeBean.getWeek(); calendarStr=realtimeBean.getMoon(); windpowerStr=windBean.getDirect()+" "+windBean.getPower(); temperatureStr=weatherBean.getTemperature(); weatherStr=weatherBean.getInfo(); WheatherBean.ResultBean.LifeBean lifeBean=resultBean.getLife(); WheatherBean.ResultBean.LifeBean.InfoBean infoBean=lifeBean.getInfo(); List<String> kongtiao=infoBean.getKongtiao(); List<String> yundong=infoBean.getYundong(); List<String> ziwaixian=infoBean.getZiwaixian(); ACStr=kongtiao.get(0)+" "+kongtiao.get(1); sportStr=yundong.get(0)+" "+yundong.get(1); lightStr=ziwaixian.get(0)+" "+ziwaixian.get(1); }
好的,我可以为你提供一些解析 JSON 数据并在 Android Studio 中显示天气预报和生活指数的基本步骤: 1. 首先,你需要获取天气数据的 API 接口,例如和风天气提供的天气预报 API:https://dev.heweather.com/docs/api/weather 2. 然后,你需要使用 Android 中提供的网络请求库,比如 Volley 或 OkHttp,来获取天气数据。你可以使用以下代码来发送 GET 请求并获取 JSON 数据: ``` String url = "your_weather_api_url_here"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理 JSON 数据 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误 } }); // 将请求添加到请求队列中 RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonObjectRequest); ``` 3. 接下来,你需要解析 JSON 数据并将它转换为 Java 对象。你可以使用 Gson 这个库来实现 JSON 数据和 Java 对象之间的转换。以下是一个使用 Gson 解析 JSON 数据的示例代码: ```java Gson gson = new Gson(); WeatherData weatherData = gson.fromJson(response.toString(), WeatherData.class); ``` 其中,WeatherData 是一个 POJO 类,它包含了从 JSON 数据中解析出来的天气信息。 4. 最后,你需要将天气信息显示在你的应用程序界面上。你可以使用 RecyclerView 或 ListView 来显示每天的天气预报信息,使用 TextView 显示当前天气信息和生活指数信息。以下是一个示例布局文件: ```xml <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/current_weather" android:layout_width="match_parent" android:layout_height="wrap_content" /> <RecyclerView android:id="@+id/daily_forecast" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/life_index" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> ``` 以上就是在 Android Studio 中解析 JSON 数据并显示天气预报和生活指数的基本步骤。希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值