title: Error with parsing JSON object
body: <p>I am working on an Android app and I need to retrieve a list of topics from my php forum, but when I run the code I get this error which I could not figure out </p>
  
  <pre><code>03-18 09:11:43.221: E/JSON(286): &lt;br /&gt;
  03-18 09:11:43.221: E/JSON(286): &lt;b&gt;Parse error&lt;/b&gt;:in  &lt;b&gt;C:\xampp\htdocs\android_login_api\include\list_of_topics.php&lt;/b&gt; on line &lt;b&gt;26&lt;/b&gt;&lt;br /&gt;
  03-18 09:11:43.322: E/JSON Parser(286): Error parsing data org.json.JSONException: Value &lt;br of     type java.lang.String cannot be converted to JSONObject
  </code></pre>
  
  <p>and here is my php </p>
  
  <pre><code>&lt;?php
  
  /*
   * Following code will list all the products
   */
  
  // array for JSON response
  $response = array();
  
  // include db connect class
  require_once __DIR__ . 'DB_Connect.php';
  
  // connecting to db
  $db = new DB_CONNECT();
  
  // get all products from products table
  if(isset($_GET['parent']))
  {
      $id = intval($_GET['parent']);}
  $result = mysql_query("select t.id, t.title, u.username as author,  from topics as t  left join user as u where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
  ") or die(mysql_error());
  
  // check for empty result
  if (mysql_num_rows($result) &gt; 0) {
      // looping through all results
      // products node
      $response["topics"] = array();
  
      while ($row = mysql_fetch_array($result)) {
      // temp user array
      $topic = array();
      $topic["tid"] = $row["t.id"];
      $topic["name"] = $row["t.title"];
      $topic["author"] = $row["u.username"];
  
  
      // push single product into final response array
  
      array_push($response["topics"], $topic);
      echo json_encode($response);
      }
      // success
      $response["success"] = 1;
  
      // echoing JSON response
      echo json_encode($response);
  } else {
      // no products found
      $response["success"] = 0;
      $response["message"] = "No topics found";
  
      // echo no users JSON
      echo json_encode($response);
  }
  ?&gt;
  </code></pre>
  
  <p>and this is the JSON parser class here I have 2 JSONOBJECT one for the user reg&amp;login and the second one for the topic list </p>
  
  <pre><code>package com.example.androidhive.library;
  
  
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.UnsupportedEncodingException;
  import java.util.List;
  
  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpGet;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.utils.URLEncodedUtils;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
  import org.json.JSONObject;
  
  import android.util.Log;
  
  public class JSONParser {
  
      static InputStream is = null;
      static JSONObject jObj = null;
      static String json = "";
  
      // constructor
      public JSONParser() {
  
      }
  
      public JSONObject getJSONFromUrl(String url, List&lt;NameValuePair&gt; params) {
  
          // Making HTTP request
          try {
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);
              httpPost.setEntity(new UrlEncodedFormEntity(params));
  
              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();
              Log.e("JSON", json);
          } 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;
  
      }
  
       public JSONObject makeHttpRequest(String url, String method,
              List&lt;NameValuePair&gt; params) {
  
          // Making HTTP request
          try {
  
              // check for request method
              if(method == "POST"){
              // request method is POST
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);
              httpPost.setEntity(new UrlEncodedFormEntity(params));
  
              HttpResponse httpResponse = httpClient.execute(httpPost);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();
  
              }else if(method == "GET"){
              // request method is GET
              DefaultHttpClient httpClient = new DefaultHttpClient();
              String paramString = URLEncodedUtils.format(params, "utf-8");
              url += "?" + paramString;
              HttpGet httpGet = new HttpGet(url);
  
              HttpResponse httpResponse = httpClient.execute(httpGet);
              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();
              Log.e("JSON", sb.toString());
              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;
  
          }
  
  
  }
  </code></pre>
  
  <p>this is the .java file from Android side</p>
  
  <pre><code>package com.example.androidhive;
  
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  
  import org.apache.http.NameValuePair;
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  
  import android.app.ListActivity;
  import android.app.ProgressDialog;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
  import android.widget.ListAdapter;
  import android.widget.ListView;
  import android.widget.SimpleAdapter;
  import android.widget.TextView;
  
  import com.example.androidhive.library.JSONParser;
  
  
  
  
  public class Topics_list extends ListActivity {
  
  // Progress Dialog
  private ProgressDialog pDialog;
  
  // Creating JSON Parser object
  JSONParser jParser = new JSONParser();
  
  ArrayList&lt;HashMap&lt;String, String&gt;&gt; TopicsList;
  
  // url to get all products list
  private static String url_all_topics = "http://10.0.2.2/android_login_api/include/list_of_topics.php";
  
  // JSON Node names
  private static final String TAG_SUCCESS = "success";
  private static final String TAG_TOPICS = "topics";
  private static final String TAG_TOPICSID = "t.id";
  private static final String TAG_TOPICTITLE = "t.title";
  private static final String TAG_TOPICAUTHOR = "u.username";
  
  // products JSONArray
  JSONArray topics = null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.topics_list);
  
  // Hashmap for ListView
  TopicsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
  // Loading products in Background Thread
  new LoadAllTopics().execute();
  
  // Get listview
  ListView lv = getListView();
  
  // on seleting single product
  // launching Edit Product Screen
  lv.setOnItemClickListener(new OnItemClickListener() {
  
      public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
      // getting values from selected ListItem
      String tid = ((TextView) view.findViewById(R.id.tid)).getText()
          .toString();
      }
     });
  
     }
  
      /*// Starting new intent
      Intent in = new Intent(getApplicationContext(),
          EditProductActivity.class);
      // sending pid to next activity
      in.putExtra(TAG_PID, pid);
  
      // starting new activity and expecting some response back
      startActivityForResult(in, 100);
      }
  });
  
  }
  
  // Response from Edit Product Activity
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  // if result code 100
  if (resultCode == 100) {
      // if result code 100 is received
      // means user edited/deleted product
      // reload this screen again
      Intent intent = getIntent();
      finish();
      startActivity(intent);
  }
  
  }*/
  
  /**
  * Background Async Task to Load all product by making HTTP Request
  * */
  class LoadAllTopics extends AsyncTask&lt;String, String, String&gt; {
  
  /**
   * Before starting background thread Show Progress Dialog
   * */
  @Override
  protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(Topics_list.this);
      pDialog.setMessage("Loading products. Please wait...");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(false);
      pDialog.show();
  }
  
  /**
   * getting All products from url
   * */
  protected String doInBackground(String... args) {
      // Building Parameters
      List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
      // getting JSON string from URL
      JSONObject json = jParser.makeHttpRequest (url_all_topics, "GET", params);
  
      // Check your log cat for JSON reponse
      Log.d("All topics: ", json.toString());
  
      try {
      // Checking for SUCCESS TAG
      int success = json.getInt(TAG_SUCCESS);
  
      if (success == 1) {
          // products found
          // Getting Array of Products
          topics = json.getJSONArray(TAG_TOPICS);
  
          // looping through All Products
          for (int i = 0; i &lt; topics.length(); i++) {
          JSONObject c = topics.getJSONObject(i);
  
          // Storing each json item in variable
          String id = c.getString(TAG_TOPICSID);
          String topict = c.getString(TAG_TOPICTITLE);
          String username = c.getString(TAG_TOPICAUTHOR);
  
          // creating new HashMap
          HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
  
          // adding each child node to HashMap key =&gt; value
          map.put(TAG_TOPICSID, id);
          map.put(TAG_TOPICTITLE, topict);
          map.put(TAG_TOPICAUTHOR, username);
  
          // adding HashList to ArrayList
          TopicsList.add(map);
          }
      } else {
          // no products found
          // Launch Add New product Activity
         /* Intent i = new Intent(getApplicationContext(),
              NewProductActivity.class);
          // Closing all previous activities
          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(i);*/
      }
      } catch (JSONException e) {
      e.printStackTrace();
      }
  
      return null;
  }
  
  /**
   * After completing background task Dismiss the progress dialog
   * **/
  protected void onPostExecute(String file_url) {
      // dismiss the dialog after getting all products
      pDialog.dismiss();
      // updating UI from Background Thread
      runOnUiThread(new Runnable() {
      public void run() {
          /**
           * Updating parsed JSON data into ListView
           * */
          ListAdapter adapter = new SimpleAdapter(
             Topics_list.this, TopicsList,
              R.layout.list_item, new String[] { TAG_TOPICSID,TAG_TOPICTITLE,
                  TAG_TOPICAUTHOR},
              new int[] { R.id.tid, R.id.title });
          // updating listview
          setListAdapter(adapter);
      }
      });
  
  }
  
  }
   }
  </code></pre>
  
  <p>latest .php code version </p>
  
  <pre><code>&lt;?php
  
  /*
   * Following code will list all the products
   */
  
  // array for JSON response
  $response = array();
  
  // include db connect class
  require_once __DIR__ . 'DB_Connect.php';
  
  // connecting to db
  $db = new DB_CONNECT();
  
  // get all products from products table
  
  if(array_key_exists('parent', $_GET)){
        $id = intval($_GET['parent']);
   } else {
   exit();}
   //echo json_encode ("wrong");
        // something to stop this processing
       // $response["success"]=0;
       //$response["message"] = "No";
   //echo json_encode((object)$response);}
  
  $result = mysql_query("select  t.id, t.title, u.username,  from topics as t  left join user as u where t.parent= '$id' and t.id2=1 group by t.id order by t.timestamp2 desc")
  or die(mysql_error());
  
  
  // check for empty result
  
  //if (mysql_num_rows($result) &gt; 0) {
      // looping through all results
      // products node
     // $response["topics"] = array();
      //echo json_encode((object)$response);
  
     // while ($row = mysql_fetch_array($result)) {
      // temp user array
      //    $topic = array();
      //    $topic["tid"] = $row["t.id"];
       //   $topic["name"] = $row["t.title"];
        //  $topic["author"] = $row["u.username"];
  
  
      // push single product into final response array
  
        /  array_push($response["topics"], $topic);
  
  //}
  if (mysqli_num_rows($result) &gt; 0) {
      // looping through all results
      // products node
      $response['topics'] = array();
      while (true) {
         $row = mysqli_fetch_array($result);
         if(!$row)break;
         // temp user array
         $topic = array();
         $topic["tid"] = $row["t.id"];
         $topic["name"] = $row["t.title"];
         $topic["author"] = $row["u.username"];
         // push single product into final response array
         array_push($response["topics"], (object)$topic);
      }
  
      // success
      $response["success"] = 1;
  
      // echoing JSON response
      echo json_encode($response);
      } else{
      // no products found
      $response["success"] = 0;
      $response["message"] = "No topics found";
  
      // echo no users JSON
      //echo json_encode($response);
      echo json_encode((object)$response);
  }
  ?&gt;
  </code></pre>
  
  <p>I hope someone could help me. Appreciate your help. Be patient on me I'm not very good.</p>