Saml92 Saml92 - 1 year ago 72
JSON Question

Android JSON returning JSON Array

I have a php service on my server which returns a JSON Array, I am now trying to connect this to my Android app.

Using the code bellow doesn't return any values:

private class getJson extends AsyncTask<String, Void, Void> {
TextView t;
String title;
protected void onPreExecute() {
// NOTE: You can call UI Element here.
t = (TextView) findViewById(;

protected Void doInBackground(String... urls) {
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost("");
ArrayList<NameValuePair> ar = new ArrayList<NameValuePair>();
ar.add(new BasicNameValuePair("uni","1"));
ar.add(new BasicNameValuePair("num","10"));
ar.add(new BasicNameValuePair("format","json"));

hp.setEntity(new UrlEncodedFormEntity(ar));
HttpResponse hr = hc.execute(hp);

InputStream is = hr.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null){
sb.append(line + "\n");
String result = sb.toString();

JSONArray ja = new JSONArray(result);
for(int i = 0; i<ja.length(); i++){
JSONObject jo = ja.getJSONObject(i);
title = jo.getString("title");
}catch(Exception e){

return null;
protected void onPostExecute(Void unused) {

The code does get called because I've put in some command line prints to check it goes into the methods. The php script also returns an array as I've checked that in a browser.

Am I doing something wrong here? This is my first time trying to link up a server so I'm kind of stabbing around in the dark with different tutorials so I've probably missed out something big.

Example of the JSON result from a browser:

{"reviews":[{"reviews":{"title":"test review","col_score":"5","col_ad":"test","night_score":"3","night_ad":"test","su_score":"4","su_ad":"test","lec_score":"5","lec_ad":"test","accom_score":"2","accom_ad":"test","sport_score":"4","sport_ad":"test","fac_score":"5","fac_ad":"test","soci_score":"4","soci_ad":"test","add_comments":"test","overall":"9"}}]}

Answer Source

You have initialised empty JSONArray

JSONArray ja = new JSONArray();

change it to

JSONArray ja = new JSONArray(result);

EDIT - Looking at your json you should parse it as follows

JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("reviews");

for(int i = 0; i<jsonArray.length(); i++){
    JSONObject jo = jsonArray.getJSONObject(i);
    JSONObject jsonObject1 = jo.getJSONObject("reviews")
    title = jsonObject1.getString("title");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download