我试着从mysql数据库中检索一些数据到android app。 这是我的PHP代码:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$players = array();
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect to the database!");
$db = mysql_select_db('arsenal') or die("Could not select DB!");
$result = mysql_query("SELECT * FROM Player");
$i = 0;
while ($row = mysql_fetch_array($result)) {
//array_push($data, $row["playerName"]);
$players[] = $row['playerName']." ".$row['surName']." ";
echo $players[$i];
$i++;
}
print(json_encode($players));
mysql_close($conn);
?>
这是我的获取数据方法:
public ArrayList<String> getPlayers(){
ArrayList<String> retRanks = new ArrayList<String>();
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/playerData.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception exc){
retRanks.add("Error in http connection " + exc.toString());
return retRanks;
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch(Exception exc){
retRanks.add("Error converting result " + exc.toString());
return retRanks;
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
retRanks.add(jArray.get(i).toString());
}
return retRanks;
} catch(JSONException exc){
retRanks.add("Error parsing data " + exc.toString());
return retRanks;
}
}
我得到了这个例外:
org.json.jsonexception value of type java.lang.string Santi cannot be converted to jsonarray
我不太确定我哪里出错了
当我向结果的值吐露时:
Santi Carzola Alex Chamberlin Theo Walcott ["Santi Carzola","Alex Chamberlin","Theo Walcott"]
答案 0 :(得分:0)
在您的PHP代码中,您在while
循环中打印每个名称一次:
echo $players[$i];
然后在打印json数组时再次打印它:
print(json_encode($players));
所以在result
中,你有以下内容:
Santi Carzola Alex Chamberlin Theo Walcott ["Santi Carzola","Alex Chamberlin","Theo Walcott"]
哪个不是JSONArray
。您需要摆脱[
之前的内容,因此请从循环中移除echo $players[$i];
,它应该可以正常工作。