-1

I found many question about this subject - but don't found one which is the same to me.

I work in Java 8 Project. I get Object[] instance arraive from sql-query, something like:

"SELECT user.name, user.age, user.client_type, user.shopping_card FROM user_account user"

(I use sqlyog)

Sometime user.client_type field or user.shopping_card return null. When I want to convert this Object[] instance to Java class I get exception:

String userName= (String) obj[1];
    int age= (Integer) obj[2];
    int type=  obj[3]== null? null: (Integer) obj[3];
    int card=  obj[4]== null?  null: (Integer) obj[4] ;
    return new UserData(userName, age, type, card);

When type is null / card is null I get an exception when debug the type/card casting row:

java.lang.NullPointerException

"SELECT user.name, user.age, 
CASE WHEN user.client_type IS NOT NULL THEN user.client_type ELSE NULL END as 
 client_type, CASE WHEN  user.shopping_card  IS NOT NULL THEN 
 user.shopping_card ELSE NULL END as shopping_card FROM user_account user"

What should I do? I must say that when all data is not null - all works well!

Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
user5260143
  • 1,048
  • 2
  • 12
  • 36
  • The way your code is, you should get some casting error as you can't convert something to int by just casting and I don't think anywhere you should be getting NullPointerException. Can you share more code? Like how you are reading data from table? – Pushpesh Kumar Rajwanshi Oct 28 '18 at 08:36
  • I wrote you that 0 " I must say that when all data is not null - all works well!" - so the problem must be at the null values – user5260143 Oct 28 '18 at 08:38

1 Answers1

0

Ok, this code has problem,

int type=  obj[3]== null? null: (Integer) obj[3];
int card=  obj[4]== null?  null: (Integer) obj[4] ;

When obj[3] or obj[4] is null, you can't assign null value to primitive types.

You need to assign -1 or 0 like this as you primitive types can't hold null values and only objects can.

Try making it this,

    int type=  obj[3]== null? -1: Integer.valueOf(obj[3]);
    int card=  obj[4]== null? -1: Integer.valueOf(obj[4]);

Also, you should use Integer.valueOf instead of just casting to Integer.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36