简体   繁体   中英

JSON error org.json.JSONException: No value for item

After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode .

The complete error:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

This my ActivityRegister.java class:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

This is the stringResponse I'm giving:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {


            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked. Any help would be appreciated.

Try this:

String retCode = jsonObject.optString("retCode");

The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException . Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.

As the crash logs suggest, you are trying to access retCode from the json but it not there.

You should use optString rather than getString , if you are not sure about the fields.

JSON中没有retCode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM