在onPostExecute方法中使用okhttp响应null解析json

时间:2017-01-12 07:29:56

标签: android android-asynctask okhttp3

我正在为OTP开发演示。我收到短信但问题是我没有得到onPostExecute方法的响应。甚至响应显示在logcat中,但我的 responseString 变量始终为null。

我的responseString Toast总是为null。请帮帮我。

这是我的 AsyncTask

     private class SendOTPTask extends AsyncTask<String, String, Void> {

        String responseString;


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setCancelable(false);
            progressDialog.setMessage("Loading....");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();


        }

        @Override
        protected Void doInBackground(String... str) {

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            Map<String, String> params = new HashMap<String, String>();
            params.put("ContactNo", str[0]);
//            params.put("name", "your name");
            JSONObject parameter = new JSONObject(params);
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(JSON, parameter.toString());
            Request request = new Request.Builder()
                    .url("http://202.131.126.46/StyleUpPlusApps.UserWebApi/api/OTP/SendOTPForRegistration")
                    .post(body)
                    .addHeader("content-type", "application/json; charset=utf-8")
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    responseString = call.request().body().toString();
//                    Log.e("response error -->", call.request().body().toString());

                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("Error")
                            .setMessage(responseString)
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // continue with delete
                                }
                            })

                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
//                    Log.e("response success -->", response.body().string());
                    responseString = response.body().string();
                    System.out.println(responseString);
                   /* if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                    {

                        responseString = response.body().string();
                        System.out.println(responseString);
                        response.body().close();

                    }*/
                }


            });


            return null;
        }

        @Override
        protected void onPostExecute(Void s) {
            super.onPostExecute(s);

            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            Toast.makeText(MainActivity.this, "" + responseString, Toast.LENGTH_SHORT).show();
            /*if (!TextUtils.isEmpty(responseString)){

                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    Toast.makeText(MainActivity.this, " "+responseString, Toast.LENGTH_SHORT).show();
                    if (jsonObject.getBoolean("IsSuccess")){
                        Toast.makeText(MainActivity.this, "OTP send...", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this, "something went wrong", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }*/


        }

    }

2 个答案:

答案 0 :(得分:1)

这个

  

client.newCall(request).enqueue(new Callback(){

asynchronous调用..在

中一段时间​​后更新responseString
  

public void onResponse(来电,响应回复)

所以发生的事情是:doInBackground将调用此行并退出,并在此之后立即调用onPostExecute,此时,异步调用不会被执行,因此 responseString 仍然 null ..明白了吗?

建议:由于您已经在使用asynctask,所以不要使用okhttp的异步调用,请使用execute()而不是enqueue(..)。

检查以获取更多详细信息: https://github.com/square/okhttp/wiki/Recipes

答案 1 :(得分:-2)

那是因为你从doInBackground()返回NULL。检查doInBackground()方法的最后一行,并将其更改为返回responseString