嗨,我有这段代码来检索 mysql 数据库,但是在解析信息时出现错误。我认为这是因为信息在一个字符串中,@Override protected Void doInBackground(String... params) {
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cs1.ucc.ie/~am32/getDB.php");
//httppost.setEntity(new UrlEncodedFromEntity(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());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result=sb.toString();
Log.i("json string", result);
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
List<String> myList= new ArrayList<String>(Arrays.asList(result.split(" ")));
JSONArray jArray = new JSONArray(myList);
System.out.println("Length"+ jArray.length());
Log.d("DB","Length"+jArray.length());
for(int i=0; i<jArray.length(); i++){
JSONObject json_data = null;
json_data = jArray.getJSONObject(i);
int id = i +1;
//String title = json_data.getString("Title");
double latitude = json_data.getDouble("Lat");
double longitude = json_data.getDouble("Lon");
//Adds proximity to POI's
ProxAlert inst = new ProxAlert();
inst.addProximityAlert(latitude,longitude, id);
//
inst.saveCoordinatesInPreferences((float)latitude, (float)longitude);
//prints to logCat
System.out.println(id+"&"+latitude+"&"+longitude);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Log.e("log_tag","Failed data as:\n"+result);
}
return null;
}
logCat 读取
09-04 19:13:13.997: E/log_tag(28100): Error parsing data org.json.JSONException: Value at 0 of type java.lang.String cannot be converted to JSONObject