网络加载数据和解析JSON格式数据案例之空气质量监测应用

一、创建一个新的项目 activity_main.xml

==”match_parent”android:orientation=”vertical” ><Button==”Reload” /><TextView==”TextView” /></LinearLayout>

二、MainActivity.java

package com.xuliugen.airpm;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URL;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;{private TextView tvPmData;(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tvPmData = (TextView) this.findViewById(R.id.tvPmData);findViewById(R.id.reload).setOnClickListener(new OnClickListener() {(View v) {reloadData();}});}() {tvPmData.setText(“Loading…”);new AsyncTask<Void, Void, String>() {@Overrideprotected String doInBackground(Void… params) {try {BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(“http://aqicn.org/publishingdata/json”).openStream(), “utf-8”));String line = null;StringBuffer contentBuffer = new StringBuffer();while ((line = reader.readLine()) != null) {contentBuffer.append(line);}reader.close();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}(String result) {if (result != null) {try {JSONArray jsonArray = new JSONArray(result);JSONObject firstJsonObject = jsonArray.getJSONObject(0);JSONArray pollutantsArray = firstJsonObject.getJSONArray(“pollutants”);JSONObject firstpollutants = pollutantsArray.getJSONObject(0);tvPmData.setText(String.format(“%s %s:%f”,firstJsonObject.getString(“cityName”),firstJsonObject.getString(“localName”),firstpollutants.getDouble(“value”)));} catch (JSONException e) {e.printStackTrace();}}};}.execute();}}

三、另一个JSON的案例代码

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);String jsonStr = “{\”name\”:\”jikexueyuan\”,\”age\”:2,\”arr\”:{1,2,3,4,5,6,\”jike\”}}”;try {JSONObject jsonObject = new JSONObject(jsonStr);String name = jsonObject.getString(“name”);System.out.println(name);JSONArray array = jsonObject.getJSONArray(“arr”);int firstValue = array.getInt(0);System.out.println(firstValue);} catch (JSONException e) {e.printStackTrace();}}

,我诚恳地希望能够获得你的原谅。只是你懂得的,对于有一些委屈,

网络加载数据和解析JSON格式数据案例之空气质量监测应用

相关文章:

你感兴趣的文章:

标签云: