问题
I can't understand the reason of NumberFormatException in this code:
SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
Below is my LogCat output:
10-30 18:04:05.600: W/System.err(23899): java.lang.NumberFormatException: Invalid int: ""
10-30 18:04:05.600: W/System.err(23899): at java.lang.Integer.invalidInt(Integer.java:138)
10-30 18:04:05.600: W/System.err(23899): at java.lang.Integer.parseInt(Integer.java:359)
10-30 18:04:05.600: W/System.err(23899): at java.lang.Integer.parseInt(Integer.java:332)
10-30 18:04:05.600: W/System.err(23899): at java.util.Calendar.getHwFirstDayOfWeek(Calendar.java:807)
10-30 18:04:05.600: W/System.err(23899): at java.util.Calendar.<init>(Calendar.java:745)
10-30 18:04:05.600: W/System.err(23899): at java.util.GregorianCalendar.<init>(GregorianCalendar.java:338)
10-30 18:04:05.600: W/System.err(23899): at java.util.GregorianCalendar.<init>(GregorianCalendar.java:314)
10-30 18:04:05.608: W/System.err(23899): at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:378)
10-30 18:04:05.608: W/System.err(23899): at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:368)
10-30 18:04:05.608: W/System.err(23899): at java.text.DateFormat.getDateInstance(DateFormat.java:462)
10-30 18:04:05.608: W/System.err(23899): at java.text.DateFormat.getDateInstance(DateFormat.java:443)
10-30 18:04:05.608: W/System.err(23899): at java.text.DateFormat.getDateInstance(DateFormat.java:426)
10-30 18:04:05.608: W/System.err(23899): at com.mycompany.mypackage.InboxFragment$15.setViewValue(InboxFragment.java:396)
Edit:
The same exception for DateFormat format = DateFormat.getDateInstance();
回答1:
change it into
SimpleDateFormat format = SimpleDateFormat.getDateInstance();
回答2:
It looks like you are trying to parse the empty String "" as an int.
See also: Unable to accept integer value through EditText
回答3:
you try this:
SimpleDateFormat.getDateInstance()
which actually return DateFormat, and you try to cast it in SimpleDateFormat, which try to convert some string to number format, which cause NumberFormatException.
This is the class hierarchy: java.lang.Object ↳ java.text.Format ↳ java.text.DateFormat ↳ java.text.SimpleDateFormat
Happy Coding ...
回答4:
.getDateInstance is inherited from DateFormat, and as such returns a DateFormat. DateFormat is a superclass of SimpleDateFormat. You can't typecast a superclass to one of its subclasses. This is what you are trying to do here and it is why you are getting this error. The compiler will trust the programmer when you cast it to SimpleDateFormat, and this is why you aren't getting any error during compilation.
To be short, you can not assign a subclass to an instance of its superclass. There are a number of ways you could attack this problem, but in this case you are simply breaking inheritance. Do not always trust the quickfixes provided by eclipse ;)
来源:https://stackoverflow.com/questions/19684888/java-numberformatexception-in-simpledateformat-getdateinstance