-1

I have a method for saving the values to ContentValues from remote server data as shown below:

public static ContentValues platformInfoToContentValues(@NonNull 
    GamePlatformInfoList platform) {
        ContentValues values = new ContentValues();

        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_ID, platform.id());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_NAME, platform.name());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_ORIGINAL_PRICE, platform.original_price());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_RELEASE_DATE, platform.release_date());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_COMPANY_NAME, platform.company().name());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_SMALL_IMAGE, platform.image().small_url());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_MEDIUM_IMAGE, platform.image().medium_url());
        values.put(TrackedPlatformEntry.COLUMN_PLATFORM_HD_IMAGE, platform.image().super_url());

        return values;
}

In the last line the platform.company() value is null which is responsible for crashing my app.

My JSON data is in the following format:

{ "company": null, "name": "PC", }

Here, the platform is GamePlatformInfoList data object which inturn "HAS-A" company as GameCompanyInfoShort data object inside it. Hence, I am using it as "platform.company().name()". How should I check for null before accessing "name()" property? Please help me.

Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
Nithin Prasad
  • 554
  • 1
  • 9
  • 22

3 Answers3

0

When you are getting your json simply write this

if(jsonObject.getString("company")!=null){
     // do your thing here
 }

You can also do this json.isNull( "field-name" ) .

Nick Asher
  • 726
  • 5
  • 19
  • Actually, I am using Google's AutoValue library to automatically convert the JSON to JSONObject. I tried all the responses given here, but it is unable to answer my question. The parameter which I have passed in the method "GamePlatformInfoList platform" is already a JSON Object but I could find the methods isNull() or getString() to check for "null". – Nithin Prasad Sep 27 '17 at 17:51
0
obj.length() == 0

or

if (jsonObject.isNull("company"))
Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
0

I used the ternary operator to handle null as shown below.

values.put(TrackedPlatformEntry.COLUMN_PLATFORM_COMPANY_NAME, platform.company() != null ? platform.company().name() : "UNKNOWN COMPANY");

It worked for me.

Pang
  • 9,564
  • 146
  • 81
  • 122
Nithin Prasad
  • 554
  • 1
  • 9
  • 22