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

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/reload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Reload" />

    <TextView
        android:id="@+id/tvPmData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.40"
        android:text="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;

public class MainActivity extends Activity {

    private TextView tvPmData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvPmData = (TextView) this.findViewById(R.id.tvPmData);

        findViewById(R.id.reload).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                reloadData();
            }
        });

    }

    private void reloadData() {
        tvPmData.setText("Loading...");
        new AsyncTask<Void, Void, String>() {

            @Override
            protected 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;
            }

            @Override
            protected void onPostExecute(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();
        }
    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。