JSON Android And Listview JSON Android And Listview json json

JSON Android And Listview


because your webservice returning an JSONArray instead of JSONObject but you are trying to convert it to JSONObject . change your getJSONFromUrl method return type to JSONArray instead of JSONObject as :

public JSONArray getJSONFromUrl(String url) { JSONArray jsonarr=null;    // Making HTTP request    // try parse the string to a JSONArray    try {        jsonarr = new JSONArray(json);    } catch (JSONException e) {    }    // return JSON String    return jsonarr;  //<<<< return JSONArray instead of JSONObject}

and call getJSONFromUrl as from onCreate of Activity :

 JSONArray json = jParser.getJSONFromUrl(url);try {    // looping through All Contacts    for(int i = 0; i < json.length(); i++){        JSONObject c = json.getJSONObject(i);        // put your parsing code here    }} catch (JSONException e) {    e.printStackTrace();}


I used the same tutorial once and i solved problem by replacing code in JSONParser class in your try-catch block. This is class is anyway useless, you can type this in onCreate() or write method in your AndroidJSONParserActivity class:

HttpClient httpclient = new DefaultHttpClient();httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);HttpGet request = new HttpGet(url);HttpResponse response = httpclient.execute(request);HttpEntity resEntity = response.getEntity();String _response=EntityUtils.toString(resEntity); // content will be consume only onceLog.i(".......",_response);JSONObject json = new JSONObject(_response);JSONArray jarray = json.getJSONArray("array_name");for(int i=0;i<jarray.length();i++){    JSONObject jb = (JSONObject) jarray.get(i);    String name = jb.getString("name");}

Anyway, you should do parsing in seperate thread instead of UI, with AsyncTask


try{        // String t;        Boolean found=false;            JSONArray jArray = new JSONArray(result);         int jArrayLength = jArray.length();        ArrayList<String> listContents = new ArrayList<String>(jArrayLength);            for(int i=0;i<jArray.length();i++){                    JSONObject json_data = jArray.getJSONObject(i);               // t[i]=json_data.getString("hotelname");            listContents.add(json_data.getString("hotelname"));            }            arr = new String[listContents.size()];            for(int i=0;i<listContents.size();i++)                arr[i]= listContents.get(i);             setListAdapter(new ArrayAdapter<String>(this,                     android.R.layout.simple_list_item_1,arr));    }    catch(JSONException e){            Log.e("log_tag", "Error parsing data "+e.toString());    }}

public void onListItemClick( ListView parent, View v, int position, long id) { Intent myIntent = new Intent(getBaseContext(), Hotelinfo.class); myIntent.putExtra("hotelname",arr[position]);

        startActivity(myIntent);        }}