来自onPostExecute()内部的startActivity()不起作用

时间:2012-06-17 17:24:13

标签: java android json android-asynctask

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

2 个答案:

答案 0 :(得分:2)

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

如果您想检查字符串"null",请使用.equals()执行此操作:if ("null".equals(result))

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

修改:为什么"null".equals(result)优于result.equals("null")?答案是:第一个是null-safe,这意味着当result为null时,它不会抛出NullPointerException。第二个将在这种情况下导致例外。

答案 1 :(得分:0)

而不是返回null你应该尝试将一个Integer值返回给onPostExecute这样的东西

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


protected void onPostExecute(Integer v) {
    if(v==1) {
    }
}