我收到错误 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());
}
}
}
在我的 Activity onCreate
中,我实例化了异步类:
new Task().execute();
对于为什么解析数据出错有什么建议吗?
谢谢
注意:使用 println() 输出变量 'result' 会按预期将 Json 输出到 logcat
最佳答案
形成你的代码:
...
catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data " + e.toString());
}
问题是它可能不是 Json 异常,而是 any 异常。实际上,不建议捕获 Exception
类型。我们应该只捕获 Exception 类的特定子类型。在我们的例子中,findViewById
抛出:NullPointerException
。因此,首先将其更改为 NullPointerException
(除了 JSONException 之外)并再次运行程序。
我会将 Error parsing data
更改为通用的内容。
假设我们在 findViewById
上没有异常并且我们的 text
不是 null
。
尝试使用Handler
更新主线程(又名 GUI):
private Handler mHandler = null;
...
mHandler = new Handler();
...
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
text = (TextView) findViewById(R.id.textView1);
JSONArray Jarray = new JSONArray(result);
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
// 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 (NullPointerException e) {
// TODO: handle exception
Log.e("log_tag", "Error " + e.toString());
}
}
}, 100); // dummy delay
作为旁注:
行 text = (TextView) findViewById(R.id.textView1);
放在循环之外 for
关于java - 解析 JSON 数据时出错 - 异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20289344/