【发布时间】:2015-06-07 19:11:43
【问题描述】:
我正在尝试通过 JSONArray 中的 Volley 从 MySql 数据库中获取信息。从表中提取行的PHP脚本如下:
<?php
ob_start();
header('Content-Type: application/json');
$con=mysqli_connect("localhost","root","","planet_db");
if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$search = $_POST['search'];
//sql query
$query = "SELECT FirstName, LastName, Username FROM users WHERE Username='$search' OR FirstName='$search'";
$result = mysqli_query($con,$query);
$jsonArr = array(array("FirstName"=>"Einie", "LastName"=>" Mini"));
while($row = mysqli_fetch_assoc($result))
{
array_push($jsonArr,$row);
}
ob_end_clean();
echo json_encode($jsonArr);
mysqli_close($con);?>
通过HTML页面在localhost上查询数据库的结果如下:
JSONArray 的第二个元素(索引 1)如上所示,但是当我尝试获取 Android 应用程序客户端接收的 JSONArray 中索引 1 处的元素时,它会抛出 JSONException:index out of bound [0. .1)。同样,当我在 PHP 脚本中编辑以下行:$jsonArr = array(array("FirstName"=>"Einie", "LastName"=>" Mini")); 到 $jsonArr=array(); 并尝试在 JSONArray 中的索引 0 处获取元素时,我收到 JSONException:index out of bound [0..0)。最后,我无法接收通过代码添加的 JSONArray 中的任何元素:
while($row = mysqli_fetch_assoc($result))
{
array_push($jsonArr,$row);
}
在我的 android 应用程序中,它会抛出 JSONException: Index out of bound 但我在 localhost 上运行它时成功获得了正确的 JSON 数组。 这是我的安卓应用程序代码:
private void performSearch()
{
final String url = "http://192.168.42.16/planet/searchPeople.php";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response)
{
//searchResults.setAdapter(new ResultListAdapter(response, Contents.this));
try {
Toast.makeText(Contents.this, response.getJSONObject(1).getString("FirstName") + " "
+ response.getJSONObject(1).getString("LastName"), Toast.LENGTH_LONG).show();
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(Contents.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Contents.this, error.toString(),Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> map = new HashMap<String, String>();
map.put("search", query);
return map;
}
};
MySingleton.getInstance(Contents.this).addToRq(request); // adding request to Volley Request Queue
}
如何摆脱这种 Index Out Of bound JSONException?任何帮助将不胜感激!
【问题讨论】:
-
你是否在 onResponse() 方法中得到 JSONArray 响应???
-
是的,我已经尝试了所有组合,请提出解决方法..
标签: php android mysql json android-volley