HttpUrlConnection和JSON制作天气预报

 一、效果展示:
二、首先创建一个activity,修改里面的布局文件,添加控件,设置id       <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="lenovo.wangmengyuan.json.WeatherActivity">    <EditTextandroid:hint="请输入城市名"android:id="@+id/city_et"android:layout_width="match_parent"android:layout_height="wrap_content"/>    <Buttonandroid:text="查询"android:id="@+id/search_btn"android:layout_width="match_parent"android:layout_height="50dp"/>    <LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="wrap_content">        <TextViewandroid:id="@+id/tianqi"android:textSize="30sp"android:text="天气:"android:layout_width="match_parent"android:layout_height="50dp"/>        <TextViewandroid:id="@+id/tianqi1"android:textSize="30sp"android:text="温度:"android:layout_width="match_parent"android:layout_height="50dp"/>        <TextViewandroid:id="@+id/tianqi2"android:textSize="30sp"android:text="风力:"android:layout_width="match_parent"android:layout_height="50dp"/>    </LinearLayout></LinearLayout>三、在activity中进行绑定控件,设置监听,在内部类中完成Http请求和Json解析,完成简易版天气预报       public classWeatherActivityextendsAppCompatActivity {privateTextViewweatherTV;privateTextViewwingTV;privateTextViewtempTV;privateButtonserrchBtn;privateEditTextcityET;privateStringweatherAPI="https://free-api.heweather.com/s6/weather/now?key=86a3c4999f6346248511a308d60856cd&location=";@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);        setContentView(R.layout.activity_weather);        bindID();serrchBtn.setOnClickListener(newView.OnClickListener() {@Overridepublic voidonClick(View view) {                String city =weatherAPI+cityET.getText().toString();newMyTAsk().execute(city);            }        });    }private voidbindID() {cityET= findViewById(R.id.city_et);serrchBtn= findViewById(R.id.search_btn);weatherTV= findViewById(R.id.tianqi);wingTV= findViewById(R.id.tianqi2);tempTV= findViewById(R.id.tianqi1);    }classMyTAskextendsAsyncTask<String, String, String> {        StringBufferstringBuffer=newStringBuffer();@OverrideprotectedString doInBackground(String... strings) {try{                URL url =newURL(strings[0]);                HttpURLConnection connection = (HttpURLConnection) url.openConnection();                InputStream inputStream =null;if(connection.getResponseCode() ==200) {                    inputStream = connection.getInputStream();//只有网络正常才能返回数据,我们才能创建输入流}else{return"network_failed";                }                InputStreamReader reader =newInputStreamReader(inputStream);                BufferedReader bufferedReader =newBufferedReader(reader);//缓存器String temp ="";while((temp = bufferedReader.readLine()) !=null) {stringBuffer.append(temp);                }                bufferedReader.close();                reader.close();                inputStream.close();            }catch(IOException e) {                e.printStackTrace();            }returnstringBuffer.toString();        }@Overrideprotected voidonPostExecute(String s) {super.onPostExecute(s);if(s.equals("network_failed")) {                Toast.makeText(WeatherActivity.this,"网络失败", Toast.LENGTH_SHORT).show();            }else{//Json解析try{                    JSONObject object =newJSONObject(s);                    JSONArray array = object.getJSONArray("HeWeather6");                    JSONObject object1 = array.getJSONObject(0);                    JSONObject object2 = object1.getJSONObject("now");                    String weather = object2.getString("cond_txt");                    String wind = object2.getString("wind_dir") + object2.getString("wind_sc") +"级";                    String temp = object2.getString("tmp");weatherTV.setText(weather);wingTV.setText(wind);tempTV.setText(temp);                }catch(JSONException e) {                    e.printStackTrace();                }            }        }    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值