In my database application I sometimes have to deal with null
strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using JTextField
for example - cannot handle null strings. (.setText(null)
fails)
(EDIT: I just noticed that JTextField
actually accepts a null
string, but the question remains for all other cases where unexpected null
values can lead to problems.)
The null values have no special meaning, they can (must) be treated as empty strings.
What is the best practice to deal with this problem? Unfortunatly I cannot change the database.
null
before calling setText()
?setText()
call?null
strings?null
values to empty strings immediatly after reading from the database?Empty String can make a good Null Object implementation for the String class, for Integer it depends on the business logic. The Null Object pattern. Create an instance of your object that represents the null state, and initialize all references to that type with a reference to the Null implementation.
A common way of avoiding the NullPointerException is to check for null: In the real world, programmers find it hard to identify which objects can be null. An aggressively safe strategy could be to check null for every object. However, this causes a lot of redundant null checks and makes our code less readable.
Overview Generally, null variables, references and collections are tricky to handle in Java code. They are not only hard to identify but also complex to deal with. As a matter of fact, any miss in dealing with null cannot be identified at compile time and results in a NullPointerException at runtime.
The int data type being one of Java's primitive types is not able to store the null. On my machine, the getInt () method returns 0 when it hits a null on the job-id. How to solve the problem? There are two ways to detect whether a null value is read. 1) Use the wasNull () method provided by the ResultSet class.
From a SQL angle try:
select ISNULL(column_name,'') from ...
If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have:
public void setFoo(String str) { this.foo = str != null ? str : ""; }
Use Beans Binding API to bind values from your entity objects to your SWING Widgets. Beanins Binding will transparently handle null values and will not replace the null with an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With