【发布时间】:2013-12-15 20:41:02
【问题描述】:
我收到错误Error parsing Data,我在解析 JSON 数据时在主要异常中发现了该错误。
但是 - 我的错误No Data Found 没有被JSONException 捕获,这让我认为数据库正在被成功读取,
我的服务器上有一个 php 文件:
<?php
mysql_connect("database_ip","database_username","database_password");
mysql_select_db("database_name");
$sql=mysql_query("select * from table");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>
在线导航到 php 文件会按预期显示 JSON 数据:
[{"KEY_ROWID":"1","KEY_NAME":"Andrew","KEY_SCORE":"100","KEY_DATE":"0000-00-00 00:00:00"},{"KEY_ROWID":"2","KEY_NAME":"Peter","KEY_SCORE":"5000","KEY_DATE":"2013-11-29 10:58:21"}]
在 Android 中,我使用 Async 任务来读取数据:
class Task extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
String url_select = "http://mywebsite.com/myphpfile.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray Jarray = new JSONArray(result);
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
text = (TextView) findViewById(R.id.textView1);
// get an output on the screen
String name = Jasonobject.getString("KEY_NAME");
text.append(name + "\n");
}
}
catch (JSONException e1) {
Toast.makeText(getBaseContext(), "NO Data Found",
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
在我的活动onCreate 我实例化了异步类:
new Task().execute();
关于为什么解析数据会出错有什么建议吗?
谢谢
注意:使用 println() 输出变量 'result' 按预期将 Json 输出到 logcat
【问题讨论】:
-
旁注:
mysql_*函数已弃用,请改用mysqli_*函数。 -
“错误解析数据”日志后打印的内容
-
只写/签入doInBackground:
Log.d("log_tag", result); -
可能是没有找到 TextView,你在第二个“catch”中捕获了所有 Exception
-
你能把你的json贴在这里吗?调试起来真的很有帮助
标签: java php android json android-asynctask