Lawrence Wong
Lawrence Wong

Reputation: 1139

exception.getmessage() return null

I am having trouble adding an object to a collection.

I encountered a java.lang.NullPointerException when I tried adding an object to a collection.

I tested and checked that redemption which is a RedemptionEntity is not null using the if condition as you can see in the code below. It returned "Not NULL!!!!!!!!!"

I went and google that a java.lang.NullPointerException occurs when you tried adding something that is null into a collection. But in this case, I don't think redemption is null. The System.out.println(ex.getMessage()); return me a null.

How do I resolve this issue? Any help here?

private Collection<RedemptionEntity> redemptionCollection; 
RedemptionEntity redemption = new RedemptionEntity();
GiftEntity GIFT = em.find(GiftEntity.class, gift);
redemption.create(date, 0);
redemption.setGift(GIFT);
em.persist(redemption);

if (redemption == null) {
                System.out.println("NULL!!!!!!!!");
            } else {
                System.out.println("Not NULL!!!!!!!!");
            }
            try {
                redemptionCollection.add(redemption); //This line is where the exception occurs...
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }

Upvotes: 0

Views: 2820

Answers (3)

EsmaeelQash
EsmaeelQash

Reputation: 498

you have to use one of the classes that implements Collection Interface: Set, List, Map, SortedSet, SortedMap, HashSet, TreeSet, ArrayList, LinkedList, Vector, Collections, Arrays, AbstractCollection

Upvotes: 0

VWeber
VWeber

Reputation: 1261

Collection is an interface. Use ArrayList or another List type for initialisiation.

ArrayList<RedemptionEntity> col = new ArrayList<RedemptionEntity> ();

or

Collection<RedemptionEntity> col = new ArrayList<RedemptionEntity> ();

Upvotes: 2

Fadi Banna
Fadi Banna

Reputation: 554

did you initialize your Collection?

 private Collection<RedemptionEntity> redemptionCollection = new ArrayList<RedemptionEntity>();

would work.

Upvotes: 1

Related Questions