我正在做一个 HttpPost 以使用异步任务从 php 服务器获取数据。基本上,php 脚本要么返回 JSON 数组,要么返回 null。当返回 json 数组时它工作正常,但是如果脚本返回 null 我的 if 语句没有被拾取并且我被返回这个错误:
解析数据 org.json.JSONException 时出错:org.json.JSONObject$1 类型的值 null 无法转换为 JSONArray
这是我的脚本的一个片段:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://localhost/test.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
if(result == "null"){
this.progressDialog.dismiss();
startActivity(new Intent(viewRandom.this, allDone.class));
}else{
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++){
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String id = Jasonobject.getString("id");
}
this.progressDialog.dismiss();
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}