0

I'm getting a JSONObject Exception in cases where the twitter value in my JSON Object media is null in my below code, even though I check to make sure I'm not assigning the value to anything if it is. Is the way I am checking correct? or how can I avoid my code throwing the exception and allow me to check if the twitter value is there or not?

if(nextActivityObject.getJSONObject("media") != null){

    media = nextActivityObject.getJSONObject("media");
    Log.d("NEXT MEDIA OBJECT NOT EMPTY", media.toString());

    if(media.getString("twitter") != null &&  media.getString("facebook") != null){
         Log.d("BOTH NOT NULL", "both not null");
         twitter = media.getString("twitter");
         facebook = media.getString("facebook");

          intent.putExtra("twitter", twitter);
          intent.putExtra("facebook", facebook);
      }
      else if(media.getString("twitter") != null){

           twitter = media.getString("twitter");
           Log.d("JUST TWITTER NOT NULL", twitter.toString());
           intent.putExtra("twitter", twitter);
      }
      else if(media.getString("facebook") != null){
          facebook = media.getString("facebook");
          Log.d("JUST FACEBOOK NOT NULL", facebook.toString());
          intent.putExtra("facebook", facebook);
      }
  }

2 Answers 2

1

You can use media.optString("twitter");. And you need another media.has("twitter") to distinguish between "no key called twitter" and "twitter key has empty string value".

To sum up, for "twitter" key, you could write

 else if(media.has("twitter")){
       twitter = media.optString("twitter");
       // here twitter is non-NULL String
       Log.d("JUST TWITTER NOT NULL", twitter.toString());
       intent.putExtra("twitter", twitter);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried media.optString("twitter") and had no luck. I checked my JSON object response and in the cases where it crashes the value is {'facebook' : ....'} and no twitter, so in that case I would use the .has to check for that "no key" case?
@ralphie9224 I've summarized again in the answer. Use opt*() instead of get*() to change exception handling to null reference / empty string / NaN value checking.
1

Use .has method to find out whether the key is in json or not. Instead of getString it is wise to use optString.

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.