【发布时间】:2012-07-31 15:18:46
【问题描述】:
我正在尝试从 php 文件中获取数据。
这是我的 PHP 代码:
$sql=mysql_query("select * from `tracking`");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
我真的需要所有数据。这是我用来获取和转换数据的代码:
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server/getData.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convertion de la réponse en String
try {
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
//sb.append(line);
}
is.close();
result=sb.toString();
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
// Affectation des données
try {
JSONArray jArray = new JSONArray(result);
Log.d("jArray", ""+jArray);
JSONObject json_data= null;
for(int i=0; i<jArray.length(); i++) {
p = new Position();
json_data = jArray.getJSONObject(i);
Log.d("js", ""+json_data);
id=json_data.getInt("id");
lat=(float) json_data.getDouble("lat");
lon=(float) json_data.getDouble("lon");
speed=(float) json_data.getDouble("speed");
alt=json_data.getDouble("alt");
time=json_data.getString("time");
date=json_data.getString("date");
p.setId(id);
p.setLat(lat);
p.setLon(lon);
p.setSpeed(speed);
p.setAlt(alt);
p.setDate(date);
p.setTime(time);
datasource.createPosition(p);
}
} catch(JSONException e1) {
Log.e("JSONEX", ""+e1);
} catch (ParseException e1) {
e1.printStackTrace();
}
这确实适用于模拟器,但不适用于我的安卓手机,我不明白原因。
现在这是我从服务器获取的 json 结果:
[{"id":"180","lat":"33.894707","lon":"-6.327312","speed":"0.00000","alt":"397","date": "29/07/2012","时间":"23:44"}]
这是在http://jsonlint.com/ 上验证的有效JSONArray
【问题讨论】:
-
JSONExeption:Java.lang.String 类型的值无法转换为 JSONArray。注意:在模拟器上我一切正常,但在电话上我得到了例外。
-
有没有办法从 result 获取数据而不通过 JSONArray ?我需要尽快让它工作,当它在电话上不起作用时我感到震惊:/
-
您可以尝试使用Gson。它是将 Json 字符串解析为对象的最佳工具之一,反之亦然。
标签: php android string jsonexception