0

非同期タスクを使用してphpサーバーからデータを取得するためにHttpPostを実行しています。基本的に、phpスクリプトはJSON配列またはnullを返します。json配列が返される場合は正常に機能しますが、スクリプトがnullを返す場合、my 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セーフです。つまり、resultがnullの場合はNullPointerExceptionをスローしません。その場合、2番目のものは例外になります。

于 2012-06-17T17:26:54.767 に答える
0

nullを返す代わりに、次のような整数値をonPostExecuteに返してみてください。

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


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