I try to build an android app that send a parameter to a php code as a where
query condition in that php code, I should get in log.i the query result but
I get the following error
org.json.JSONException: Value john of type java.lang.String cannot be converted to JSONObject
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "3");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONTransmitter class.
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://192.168.1.10:89/b.php";
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
Toast.makeText(null, resFromServer, Toast.LENGTH_LONG);
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
}
php code
<?php
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$j_out = new stdClass();
$j_out->part_name= $row['part_name'];
echo json_encode($j_out);
?>