在List视图中显示JSON Array的值

时间:2015-03-13 09:30:52

标签: android arrays json android-listview

public class MainActivity extends Activity{

    String custid, from;
    Button btnPost;
    String identifier;
    Person person;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnPost = (Button) findViewById(R.id.testbutton);
        btnPost.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                    new HttpAsyncTask().execute("http://example.com/api/customer/example/");
            }
        });
    }

    public static String POST(String url, Person person){
        InputStream inputStream = null;
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String json = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("identifier", person.getIdentifier());
            jsonObject.accumulate("customer_id", person.getId());
            jsonObject.accumulate("from", person.getFrom());
            json = jsonObject.toString();
            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private class HttpAsyncTask extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String... urls) {

            person = new Person();
            person.setIdentifier(identifier.toString());
            person.setId(custid.toString());
            person.setFrom(from.toString());

            return POST(urls[0], person);
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject json = new JSONObject(result);
                String respResult=json.getString("result");

                if(respResult.equals("ok")) {
                    Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show();
                    //loop json array keywords
                    //get the values of keyword and creation date in a listview
                }
                if(respResult.equals("error")) {
                    String respError=json.getString("error");
                    Toast.makeText(getApplicationContext(), respError, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;
    }
}

这是我完整的MainActivity类。 当我点击按钮时,我得到以下JSON格式的结果

{"result":ok","keyword":[{"business_id":"1","keyword_id":"1","created_time":"2015-03-11 14:57:58","keyword":"abc"}]}

当我单击Button时,我想循环到这个JSON数组并只提取关键字和created_time并在ListView中显示它。

任何人都可以告诉我这是怎么做到的? 请告诉我如何通过修改代码来为此构建Listview。

非常感谢。

2 个答案:

答案 0 :(得分:1)

private class Category_Three extends AsyncTask<String, Void, String> {



    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = ProgressDialog.show(Menu_activity.this, "", "");
        pDialog.setContentView(R.layout.progress);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {

        String text = "";
        String data = "";
        BufferedReader reader = null;

        try {

            URL url = new URL("www.example.com/fil/example.php");

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(data);
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            text = sb.toString();
        } catch (Exception ex) {

        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }

        return text;
    }

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();

        JSONObject jsonResponse;

        try {

            jsonResponse = new JSONObject(result);

            Log.d("RESPONSE----", jsonResponse.toString());

            JSONArray jsonMainNode = jsonResponse.optJSONArray("JSON_ARRAY_KEY_NODE_NAME");

            int lengthJsonArr = jsonMainNode.length();
            String img, desc, title, city;
            String OutputData = "";

            for (int i = 0; i < lengthJsonArr; i++) {

                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                OutputData = jsonChildNode.optString("result").toString();

                img = jsonChildNode.optString("img").toString();

                title = jsonChildNode.optString("ads_title").toString();



                lstNews_3.add(title);
            }

            if (OutputData.equalsIgnoreCase("ok")) {

                /*here listView3 is your list view object*/

                listView3.setAdapter(adapter3);

            } else {
                Toast.makeText(getBaseContext(), "No Record Found",
                        Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();

        }

    }
}

答案 1 :(得分:0)

按照This教程解释如何解析JSON响应。

然后使用适配器将值设置为ListView。