2017-04-03 14 views
0

JSON 응답을 약간 조정하면 오류가 W/System.err: org.json.JSONException: No value for retCode으로 변경되었습니다.JSON 오류 org.json.JSONException : 항목이 없습니다.

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 

이 내 ActivityRegister.java 클래스 :

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."); 
     } 
    } 

내 기본 URL은 다음과 같습니다 : public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; 제공되고

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."); 
         } 
        } 

       } 
      }); 
     } 
    } 
} 

이 내가주고있어 stringResponse입니다 stringResponse가 요구 될 때. 도움이 될 것입니다.

답변

2

이 시도 :

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.

0

이 JSON 로그 건의 사고로

1

에는 retCode 없다, 당신은 그것을하지 거기 JSON에서 retCode에 액세스하려고 만한다.

필드에 대해 잘 모르는 경우 getString 대신 optString을 사용해야합니다.

관련 문제