从Android上的URL简单解析JSON并在列表视图中显示 [英] Simple parse JSON from URL on Android and display in listview

查看:27
本文介绍了从Android上的URL简单解析JSON并在列表视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析从我的 Android 应用程序中的 URL 获取的 JSON 结果...

我在网上尝试了几个例子,但无法让它工作.JSON 数据如下所示:

<预><代码>[{"city_id": "1","city_name": "诺伊达"},{"city_id": "2","city_name": "德里"},{"city_id": "3","city_name": "加济亚巴德"},{"city_id": "4","city_name": "古尔冈"},{"city_id": "5","city_name": "Gr. Noida"}]

获取 URL 并解析 JSON 数据的最简单方法是什么,将其显示在列表视图中

解决方案

您可以使用 AsyncTask,您必须自定义以满足您的需求,但类似于以下内容

<小时>

异步任务有三个主要方法:

  1. onPreExecute() - 最常用于设置和启动进度对话框

  2. doInBackground() - 建立连接并从服务器接收响应(不要尝试将响应值分配给 GUI 元素,这是一个常见错误,无法在后台完成线程).

  3. onPostExecute() - 这里我们脱离了后台线程,因此我们可以使用响应数据进行用户界面操作,或者简单地将响应分配给特定的变量类型.

<小时>

首先我们将启动类,初始化一个 String 以保存方法之外但在类内的结果,然后运行 ​​onPreExecute() 方法设置一个简单的进度对话框.

class MyAsyncTask 扩展了 AsyncTask{private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);InputStream inputStream = null;字符串结果 = "";受保护的无效 onPreExecute() {progressDialog.setMessage("正在下载您的数据...");progressDialog.show();progressDialog.setOnCancelListener(new OnCancelListener() {公共无效 onCancel(DialogInterface arg0){MyAsyncTask.this.cancel(true);}});}

然后我们需要设置连接以及我们想要如何处理响应:

 @Override受保护的 Void doInBackground(String... params) {String url_select = "http://yoururlhere.com";ArrayListparam = new ArrayList();尝试 {//设置HTTP post//HttpClient 不推荐使用.需要改成URLConnectionHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url_select);httpPost.setEntity(new UrlEncodedFormEntity(param));HttpResponse httpResponse = httpClient.execute(httpPost);HttpEntity httpEntity = httpResponse.getEntity();//读取内容 &日志inputStream = httpEntity.getContent();} catch (UnsupportedEncodingException e1) {Log.e("UnsupportedEncodingException", e1.toString());e1.printStackTrace();} catch (ClientProtocolException e2) {Log.e("ClientProtocolException", e2.toString());e2.printStackTrace();} catch (IllegalStateException e3) {Log.e("IllegalStateException", e3.toString());e3.printStackTrace();} catch (IOException e4) {Log.e("IOException", e4.toString());e4.printStackTrace();}//使用 String Builder 将响应转换为字符串尝试 {BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);StringBuilder sBuilder = new StringBuilder();字符串行 = null;while ((line = bReader.readLine()) != null) {sBuilder.append(line + "
");}inputStream.close();结果 = sBuilder.toString();} 捕获(异常 e){Log.e("StringBuilding & BufferedReader", "错误转换结果" + e.toString());}}//受保护的 Void doInBackground(String... params)

最后,在这里我们将解析返回,在这个例子中它是一个 JSON 数组,然后关闭对话框:

 protected void onPostExecute(Void v) {//解析JSON数据尝试 {JSONArray jArray = new JSONArray(result);for(i=0; i < jArray.length(); i++) {JSONObject jObject = jArray.getJSONObject(i);String name = jObject.getString("name");String tab1_text = jObject.getString("tab1_text");int active = jObject.getInt("active");}//结束循环this.progressDialog.dismiss();} catch (JSONException e) {Log.e("JSONException", "错误:" + e.toString());}//捕获 (JSONException e)}//protected void onPostExecute(Void v)}//class MyAsyncTask extends AsyncTask

I'm trying to parse a JSON result fetched from a URL in my Android app...

I have tried a few examples on the Internet, but can't get it to work. The JSON data looks like this:

[
    {
        "city_id": "1",
        "city_name": "Noida"
    },
    {
        "city_id": "2",
        "city_name": "Delhi"
    },
    {
        "city_id": "3",
        "city_name": "Gaziyabad"
    },
    {
        "city_id": "4",
        "city_name": "Gurgaon"
    },
    {
        "city_id": "5",
        "city_name": "Gr. Noida"
    }
]

What's the simplest way to fetch the URL and parse the JSON data show it in the listview

解决方案

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.


First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "
");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

这篇关于从Android上的URL简单解析JSON并在列表视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆