【发布时间】:2015-12-16 11:45:46
【问题描述】:
我尝试构建一个将参数发送到 php 代码作为 where 的 android 应用程序
该php代码中的查询条件,我应该在log.i中获取查询结果,但是
我收到以下错误
org.json.JSONException:java.lang.String 类型的值 john 无法转换为 JSONObject
主活动
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 类。
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代码
<?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);
?>
【问题讨论】:
标签: php android json android-json