I’m trying to access a static method in a Utils class I created:
public class Utils{
public static Date convertToDate(String dateString, String dFormat){
SimpleDateFormat dateFormat = new SimpleDateFormat(dFormat, Locale.US);
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateString);
Log.i("date", "convertedDate = " + convertedDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return convertedDate;
}
}
When I attempted to access this method like so:
Utils.convertToDate("03-04-2012", "mm-dd-yyyy");
I get a null pointer exception.
How could this be???
My guess is that it’s not that method that’s throwing the exception – but the fact that it returns null and you’re using the return value, like this:
That’s the problem with effectively swallowing exceptions and pretending nothing’s wrong. Note that your format should be “MM-dd-yyyy” instead of “mm-dd-yyyy”. Also note that your code would be simpler if you declared
convertedDatewithin yourtryblock and just returned it, instead of waiting to come out of thetryblock before returning.(Having said all of this, I wouldn’t have expected that code to throw an exception. It wouldn’t give you the value you wanted, but it should be okay to actually parse… If you could produce a short but complete program demonstrating the problem, that would really help.)