我正在尝试从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();
}
这真的适用于模拟器但不在我的Android手机上,我没有理由 现在这是来自服务器的json结果:
上有效的[{ “ID”: “180”, “LAT”: “33.894707”, “LON”: “ - 6.327312”, “速度”: “0.00000”, “ALT”: “397”, “日期”: “29/07/2012”, “时间”: “23时44分”}]
JSONArray
验证
答案 0 :(得分:2)
我发现JSON出了什么问题。 我在开始时发现了一个字符“?”添加到代码中的某处,直到我将logCat条目存储到文件中才能看到它。所以我添加了代码行,现在工作正常。
result = result.substring(1);
我希望将来可能会有人帮助Waqas
答案 1 :(得分:0)
这一行:
while(result.charAt(0)!='[') //or result.charAt(0)!='{'
{
result = result.substring(1);
Log.d("Tag1", "remove 1st char");
}
后:
result = sb.toString();
变成这样:;
result = sb.toString();
while(result.charAt(0)!='[')
{
result = result.substring(1);
Log.d("Tag1", "remove 1st char");
}