通过json解析和asynctask填充listview

时间:2013-12-14 08:12:12

标签: android json android-listview android-asynctask

我想从here解析。但我有以下例外:

no values for earthquakes.

UpdateFromSite:

 public class UpdateFromSite extends Activity {
    ListView list;
    TextView name;
    TextView description;
    TextView price;
        Button Btngetdata;
        ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>();
        //URL to get JSON Array
       private static String url = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo";
        //JSON Node Names
      private static final String TAG_ITEM = "earthquakes";
    private static final String TAG_NAME = "eqid";
    private static final String TAG_DESCRIPTION = "src";
        private static final String TAG_PRICE = "magnitude";
    JSONArray earthquakes = null;

        @Override
        protected void onCreate(Bundle bundle) {
            super.onCreate(bundle);
            setContentView(R.layout.updateapp);
            newItemlist = new ArrayList<HashMap<String, String>>();
            Btngetdata = (Button)findViewById(R.id.getdata);
            Btngetdata.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //check internet connection
                    Boolean isInternetPresent = false;
                    ConnectionDetector cd;
                    cd = new ConnectionDetector(getApplicationContext());
                    isInternetPresent = cd.isConnectingToInternet();

                    if (isInternetPresent) {
                        new JSONParse().execute();  }

                    else {
                        Toast.makeText(getApplicationContext(),"You don't have internet connection.",Toast.LENGTH_SHORT).show();
                                         }
                         }
            });
        }



        private class JSONParse extends AsyncTask<String, String, JSONObject> {


            private ProgressDialog pDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();


                name = (TextView)findViewById(R.id.nameNewItem);
                description = (TextView)findViewById(R.id.descriptionNewItem);
                price = (TextView)findViewById(R.id.priceNewItem);
                pDialog = new ProgressDialog(UpdateFromSite.this);
                pDialog.setMessage("Getting Data ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
            @Override
            protected JSONObject doInBackground(String... args) {
                try {
                    JSONParser jParser = new JSONParser();
                    // Getting JSON from URL
                    JSONObject json = jParser.getJSONFromUrl(url);
                    return json;
                }   catch (Exception ex){
                    Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
                    return null;
                }

            }
            @Override
            protected void onPostExecute(JSONObject json) {
                pDialog.dismiss();
                try {
                    // Getting JSON Array from URL
                    earthquakes = json.getJSONArray(TAG_ITEM);
                    for(int i = 0; i < earthquakes.length(); i++){
                        JSONObject c = earthquakes.getJSONObject(i);

                        // Storing  JSON item in a Variable
                        String name = c.getString(TAG_NAME);
                        String description = c.getString(TAG_DESCRIPTION);
                       Double price = c.getDouble(TAG_PRICE);

                        // Adding value HashMap key => value
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESCRIPTION, description);
                        map.put(TAG_PRICE, Double.toString(price));
                        newItemlist.add(map);
                        list=(ListView)findViewById(R.id.listupdate);
                        ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, newItemlist,
                                R.layout.updateapprow,
                                new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
                                R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem});
                        list.setAdapter(adapter);

                    }
                }

                catch (Exception e) {
                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }


        }

JSONParser:

 public class JSONParser {
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
        // constructor
        public JSONParser() {
        }
        public JSONObject getJSONFromUrl(String url) {
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            // return JSON String
            return jObj;
        }

    }

我认为我的问题在于hashmap。请帮帮我。

1 个答案:

答案 0 :(得分:0)

JSON解析部分:

ArrayList<HashMap<String,String>> alist=new ArrayList<HashMap<String,String>>();  
     try {
                JSONObject job = new JSONObject(jobj);
    JSONArray jArray = job.getJSONArray("earthquakes");
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    String eqid = json_data.getString("eqid");
                    String magn=json_data.getString("magnitude");
                    HashMap<String, String>map=new HashMap<String, String>();
                    map.put("eqid",eqid);
                    map.put("magnitude", magn);
                    alist.add(map);
                }

现在使用simpleadapter填充listview一定要创建一个xml布局,其中包含listview行的两个textview:

ListView list = (ListView) findViewById(R.id.listView1);
            final SimpleAdapter sd;
            sd=new SimpleAdapter(youractivity.this,alist,R.layout.item_list,new String[]{"eqid","magnitude"},new int[]{R.id.eqid,R.id.magnitude});
            list.setAdapter(sd);

将arraylist <hashmap<string,string>> your_map声明为全局变量。在doInBackground()方法中执行json下载部分,并在onPostExecute()方法中更新listview。这应该没有任何问题!