I try to write mothod that extract all the coupon list from db. this is the method:
public ArrayList<Coupon> getAllCoupons() {
Connection connection = null;
ArrayList<Coupon> coupons = new ArrayList<Coupon>();
PreparedStatement statement = null;
ResultSet result = null;
Coupon coupon = new Coupon();
try {
connection = ConnectionPool.getInstance().getConnection();
String sqlStatement = "select * from coupons";
statement = connection.prepareStatement(sqlStatement);
result = statement.executeQuery();
while (result.next()) {
System.out.println("result arrived");
coupon = extractCouponFromResult(result);
coupons.add(coupon);
System.out.println(coupon);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
// closing all resources
ConnectionPool.closeResources(statement);
}
}
return coupons;
}
Another method gets the results and organizes everything in the array:
public static Coupon extractCouponFromResult(ResultSet result) {
Coupon coupon = null;
try {
// extract the data from db to coupon object
coupon = new Coupon();
coupon.setId(result.getInt("id"));
coupon.setCompanyId(result.getInt("company_id"));
// coupon.setCategory(Category.valueOf(result.getString(3)));a
coupon.setCategory(Category.valueOf(result.getString("CATEGORY_ID").toUpperCase()));
coupon.setTitle(result.getString("title"));
coupon.setDescription(result.getString("description"));
coupon.setStartDate(result.getDate("start_date"));
coupon.setEndDate(result.getDate("end_date"));
coupon.setAmount(result.getInt("amount"));
coupon.setPrice(result.getDouble("price"));
coupon.setImage(result.getString("image"));
} catch (Exception e) {
e.printStackTrace();
}
return coupon;
}
I get this error: java.lang.IllegalArgumentException: No enum constant com.chana.coupons.beans.Category.3 Coupon [id=14, companyId=3, category=null, title=null, description=null, startDate=null, endDate=null, amount=0, price=0.0, image=null] result arrived Coupon [id=15, companyId=3, category=null, title=null, description=null, startDate=null, endDate=null, amount=0, price=0.0, image=null] result arrived Coupon [id=16, companyId=3, category=null, title=null, description=null, startDate=null, endDate=null, amount=0, price=0.0, image=null] result arrived .....
my enum class is:
package com.chana.coupons.beans;
public enum Category {
FOOD(1), ELECTRICITY(2), RESTAURANT(3),VACATION(4);
private int id;
private Category(int id) {
this.id = id;
}
public int getId() {
return id;
}
public int getId(Category category) {
return id;
}
public void setId(int id,Category category ) {
this.id = id;
}
public static Category fromString(String string) {
for (Category c : Category.values()) {
if(c.equals(string)) {
return c;
}
}
return null;
}
}
In the database everything appears according to the enum.
I would be happy for help on how to resolve this