Jaidyn Belbin Jaidyn Belbin - 3 months ago 9
Android Question

NPE while attempting to call replaceAll() on ArrayList<String>

Okay, I understand what an NPE is, and why they are caused (most of the time), but I cannot figure out why this is happening.

I have an ArrayList of Strings, which is definitely not empty, because I have been displaying each element in a ListView previously.

I am using a custom Comparator:

public static class NumericalPodcastSort implements Comparator<String> {

@Override
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}

int extractInt(String s) {
String num = s.replaceAll("\\D", ""); << This is where the NPE is occurring.
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
}


to sort the integer part of each String in descending order (1, 2, 3, etc.), as shown here

This is where I do the formatting and sorting of the ArrayList, before returning it and using it elsewhere.

public ArrayList<String> formatMindhiveTitles(ArrayList<String> arrayList) {

ArrayList<String> formattedTitles = new ArrayList<>();

for (int i = 0; i < arrayList.size(); i++) {

String title = arrayList.get(i);

formattedTitles.add(StringUtils.substringBetween(title, "mindhive podcast/", ".mp3"));
}

if (!formattedTitles.isEmpty()) {
Collections.sort(formattedTitles, new FragmentUtilities.NumericalPodcastSort());
return formattedTitles;
}

return new ArrayList<>();
}


I have shuffled the
Collections.sort()
call around to several different places, but I continually receive

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.replaceAll(java.lang.String, java.lang.String)' on a null object reference


I apologise if this is a simple fix, but for the life of me, I cannot work out why this is happening. It's not an issue of me using
ArrayList<String>
instead of
List<String>
is it? I shouldn't think so, but I'm not sure.

Answer

StringUtils.substringBetween() specifies several cases in which it will return null. Presumably that's causing null values to be added to your formattedTitles list, which in turn cause an NPE in your extractInt() method.