3
String value = myInput.getText().toString();

I want to put string value into JSONObject.put("STRING",value) method but it's not working..

See the attached screen shot and tell how to resolve this.

enter image description here

6
  • use try catch for that Commented Jul 7, 2016 at 11:30
  • you forgot to attach screenshot. Commented Jul 7, 2016 at 11:31
  • My question is not about what error is coming.. Commented Jul 7, 2016 at 11:31
  • why try catch is compulsory for that Commented Jul 7, 2016 at 11:36
  • because may be Exception comes so catch block handle Commented Jul 7, 2016 at 11:36

3 Answers 3

5

Add try.. catch

String data = "";
String val = "hello";
            try {
                JSONObject j = new JSONObject(data);
                j.put("VAL", val);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
Sign up to request clarification or add additional context in comments.

1 Comment

because may be Exception comes so catch block handle
4

You should wrap the code inside try-catch

try {
    JSONObject j = new JSONObject(data);
} catch (JSONException e) {        
    e.printStackTrace();
}

Why try-catch is compulsary??

There are 2 kinds of exceptions: Checked and Unchecked.

  1. Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.

  2. Unchecked exception is a Runtime Exception which means these are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.

JSONException is a type of Checked exception. Checked exceptions needs to be handled at compile time itself.

new JSONObject(data) will throw JSONException if the parse fails or doesn't yield a JSONObject. So it is recommended to wrap it inside a try-catch block at compile time itself & the underlying IDE will show an error message for the same.

Comments

2

Put your code in try.. catch block because may be Exception occur

 try{
         JSONObject params = new JSONObject(data);  
    }
 catch (JSONException e)
    {
        e.printStackTrace();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.