I am doing an HttpPost to get data from a php server using async task. Basically the php script will either return a JSON array or null. It works fine when the json array is returned, however if the script returns null my if statement is not being picked up on and I am being returned this error:
Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is a snippet of my script:
@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());
}
}
}
Change
if(result == "null")toif(result == null).If you want to check for the string
"null"do it with.equals():if ("null".equals(result))I am not sure if you really send a “null” string back from your server but anyway. As you might end returning
null(not the string!), you should check for that, too.Edit: Why is
"null".equals(result)better thanresult.equals("null")? The answer is: the first one is null-safe which means it will not throw a NullPointerException whenresultis null. The second one will result in an exception in that case.