0

我正在做一个 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());
        }
        }
}
4

2 回答 2

2

更改if(result == "null")if(result == null)

如果要检查字符串"null",请使用.equals()if ("null".equals(result))

我不确定您是否真的从服务器发回了“null”字符串,但无论如何。由于您可能结束返回null(不是字符串!),您也应该检查它。

编辑:为什么"null".equals(result)优于result.equals("null")?答案是:第一个是 null 安全的,这意味着它在为 null 时不会抛出 NullPointerException result。在这种情况下,第二个将导致异常。

于 2012-06-17T17:26:54.767 回答
0

而不是返回 null 您应该尝试将 Integer 值返回给 onPostExecute 类似这样的东西

@Override
public Integer doInBackground(String...params){
    .......
    .......
    return 1;
}


protected void onPostExecute(Integer v) {
    if(v==1) {
    }
}
于 2012-06-17T17:46:43.740 回答