【发布时间】:2013-09-11 19:06:28
【问题描述】:
我会尝试从 mysql 数据库中检索一些数据到可能的 android 应用程序。 这是我的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"]
【问题讨论】:
-
你能在这行之前打印
result的内容吗:JSONArray jArray = new JSONArray(result);? -
是的,我可以(当我检查结果中的值时,我可以看到值)它只是在它隐藏它时,它有问题
-
好的,但是你能把它添加到你上面的帖子中,这样我们就可以看到它的内容了吗?
-
我已经编辑了帖子,不知道这是否是它的意思
-
其中一个问题是
Santi Carzola Alex Chamberlin Theo Walcott在[字符之前,所以对于Android,它不是JSONArray 而是String