java解析json获取天气预报城市代码_利用json获取天气信息

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="城市名称:" />

android:id="@+id/tx_cityname"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:ems="10" >

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="最高温度:" />

android:id="@+id/tx_height"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:ems="10" />

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="最低温度:" />

android:id="@+id/tx_low"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:ems="10" />

android:id="@+id/button_refresh"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:gravity="center"

android:text="获取实时天气信息" >

本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,获得到成都的最高温度和最低温度,效果图例如以下:

49bfbe92656d542443404459d66ce256.png

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供一些解析 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、付费专栏及课程。

余额充值