代码之家  ›  专栏  ›  技术社区  ›  Veer3383

在列表视图中显示JSON数组的值

  •  0
  • Veer3383  · 技术社区  · 10 年前
    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 回复  |  直到 10 年前
        1
  •  0
  •   Bhaskar    10 年前

    跟随 This 该教程解释了如何解析JSON响应。

    然后使用Adapter为ListView设置值。

        2
  •  0
  •   Fahim    10 年前
    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();
    
            }
    
        }
    }