Search code examples
androidnullorg.jsonjsonexception

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

Solution

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