【发布时间】:2016-03-03 15:56:59
【问题描述】:
所以我正在开发一个从 xampp 服务器上的 MySQL 数据库中检索数据的 android 应用程序。这是来自android main的代码,
Button scanButton = (Button) findViewById(R.id.scanButton);
String findUrl = "http://myIPaddress/webservice/findItem.php";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
scanButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
JsonObjectRequest jsonObjectrequest = new JsonObjectRequest(Request.Method.POST,
findUrl, new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response){
try{
//retrieve the items table from the database
JSONArray items = response.getJSONArray("items");
int i = 2;
//retrieve the 3rd row in the table
JSONObject item = items.getJSONObject(i);
String name = item.getString("name");
//send a LogCat message containing the name of the row
Log.d("name",name);
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
//in case of an error, send a logcat message containing the error
Log.d("error","" + error.getMessage());
}
});
requestQueue.add(jsonObjectrequest);
}
});
}
php 脚本位于 webservice 文件夹中,该文件夹位于 xampp 文件夹的 htdocs 文件夹中。这是connection.php的脚本(声明并设置数据库的连接),
<?php
define('hostname', 'localhost');
define('user','root');
define('password','');
define('databaseName','webservice');
$connect = mysqli_connect(hostname, user, password, databaseName);
?>
和 findItem.php 的脚本(从我的本地主机 phpmyadmin 中的“webservice”数据库返回“items”表),
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
showItem();
}
function showItem(){
global $connect;
$query = "Select * FROM ITEMS";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("items"=>$temp_array));
mysqli_close($connect);
}
?>
我遇到的错误发生在运行时。当我在我的 android 模拟器中单击按钮时,logcat 消息不是“项目”表第三行的名称。有一条错误消息,但错误最终为空。我的问题基本上是什么可能导致这种情况?我已确保 php 脚本位于正确的位置(xampp/htdocs/webservice),IP 地址正确,apache 和 mysql 的 xampp 服务器已打开,正确的权限已写入 android 清单文件,以及在名为“webservice”的数据库中存在至少 3 行的“items”表。感谢您提供任何反馈,提前感谢您。
【问题讨论】: