I have a problem with parsing my JSon Data in an Android application. I use a PHP script to get the Data from mysql and put it in a JSON. The problem is I can print the result and I see all the items that are in my table people.
but when the data is passed to the stringbuilder everything goes wrong. Afther parsing JSON’s array say’s that there is only one object in my Array?
I hope you can help me or give me some advice.
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.1.10/getAllPeople.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int id;
double Lat;
double Long;
String hulp = "";
v3 = (TextView) findViewById(R.id.tv3);
//v3.setText("Resultaat: " + result);
try{
jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getInt("id");
Long = json_data.getDouble("long");
Lat = json_data.getDouble("lat");
hulp = hulp + "\n" + "Long: " + Long + " Lat: " + Lat;
mob.add(new MobieleFlitsers(id,Long,Lat));
}
for(int i=0;i<mob.size();i++){
hulp = " " + mob.size();
}
v3.setText(hulp);
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "Geen locatie's gevonden" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
I have added the PHP code because it stores the wrong JSON format.
$q=mysql_query("SELECT * FROM people");
//while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//print(json_encode($output));
//mysql_close();
if (!$q) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($q) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_row($q)) {
$output[]=$row;
print(json_encode($output));
}
mysql_close();
}
}
?>
to complete jakeclarkson answer , in your PHP this
prints the entire json so far at each row, so basically, it print [1][1,2][1,2,3]… instead of only the last one. You simply need to extract your print after $output is complete: