我正在做一个 HttpPost 使用异步任务从 php 服务器获取数据。基本上,php 脚本将返回 JSON 数组或 null。当返回 json 数组时它工作正常,但是如果脚本返回 null,则我的 if 语句不会被拾取,并且我将返回此错误:
解析数据 org.json.JSONException 时出错:org.json.JSONObject$1 类型的值 null 无法转换为 JSONArray
这是我的脚本的 fragment :
@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());
}
}
}
最佳答案
将 if(result == "null")
更改为 if(result == null)
。
如果您想检查字符串"null"
,请使用.equals()
:if ("null".equals(result))
我不确定您是否真的从服务器发回了“空”字符串,但无论如何。由于您可能最终返回 null
(不是字符串!),因此您也应该检查这一点。
编辑:为什么"null".equals(result)
比result.equals("null")
更好?答案是:第一个是空安全的,这意味着当result
为空时它不会抛出NullPointerException。在这种情况下,第二个将导致异常。
关于java - onPostExecute() 内部的 startActivity() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11073322/