0

I'm getting an NullPointerException when im trying to sort my arraylist with "ObjectEpisodes" in it.

The null pointer appears when im trying to sort the ArrayList but then some of the objects dont have a date to sort on. I'm getting those information via JSON and API calls.

What is the best way to handle those null pointers?

My Object implements Comparable:

        public Date getDateTime() {
            return convertDate(getAirdate());
        }  

        public Date convertDate(String date)
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date inputDate = null;
            try {
                inputDate = dateFormat.parse(date);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return inputDate;
        }

        @Override
        public int compareTo(SickbeardEpisode another) {
            return getDateTime().compareTo(another.getDateTime());
        }

Here is were i call Collections.sort(episodes):

private static List<ObjectEpisodes> parseEpisodes(String url) {
        List<ObjectEpisode> episodes = new ArrayList<ObjectEpisode>();

        String json = download(url);

        try {
            JSONObject result = new JSONObject(json);
            JSONObject resultData = result.getJSONObject("data");
            Iterator<String> iter = resultData.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                JSONObject value = resultData.getJSONObject(key);
                ObjectEpisode episode = new ObjectEpisode(value);
                series.add(serie);
            }
        }
        catch (JSONException e) 
        {
            e.printStackTrace();
        }

        Collections.sort(episodes);

        return series;
    }
Timmeeh93
  • 223
  • 1
  • 4
  • 14

2 Answers2

1

If you need to handle null I would change this

@Override
public int compareTo(SickbeardEpisode another) {
  return getDateTime().compareTo(another.getDateTime());
}

to something like

@Override
public int compareTo(SickbeardEpisode another) {
  Date d = getDateTime();
  if (d == null) {
    if (another == null || another.getDateTime() == null) return 0;
    return -1;
  }
  return d.compareTo(another.getDateTime());
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

I believe the NPE was generated while you were parsing the date values:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.parse(null) // java.lang.NullPointerException

You could detect null, then return null or defencive value in this case, it depends on you business logic. After you properly handle the NPE, another thing you should consider is where to place the null values after being sorted, in front of or back of the collection.

George Sun
  • 116
  • 1
  • 5