Rafa
Rafa

Reputation: 3339

Android getting JSONObject Exception

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

Upvotes: 0

Views: 351

Answers (2)

Jiju Induchoodan
Jiju Induchoodan

Reputation: 4266

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

Upvotes: 1

timrau
timrau

Reputation: 23058

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

Upvotes: 1

Related Questions