populate listview via json parsing and asynctask

i want to parse from here. but i have following exception:

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;
        }

    }

i think my problem is in hashmap. please help me.


1 Solution
Solution

JSON parsing part:

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);
                }

Now for populating to listview using simpleadapter be sure to create an xml layout with two textviews for the listview row:

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);

declare the arraylist<hashmap<string,string>> your_map as a global variable. do the json downloading part in the doInBackground() method and update your listview in the onPostExecute() method. This should work without any issues!