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);
      }
  }
timrau
  • 22,578
  • 4
  • 51
  • 64
Rafa
  • 3,219
  • 4
  • 38
  • 70

2 Answers2

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);
  }
timrau
  • 22,578
  • 4
  • 51
  • 64
  • 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? – Rafa Oct 03 '15 at 03:20
  • @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. – timrau Oct 03 '15 at 03:25
1

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

Jiju Induchoodan
  • 4,236
  • 1
  • 22
  • 24