Search code examples
javaandroidclasssqliteopenhelper

Constructor cannot be applied


i was doing this tutorial on Android Studio Development Essentials 6th Edition, the tutorial was about SQLiteDatase so i wrote evrything but i kept on getting an error whenever i try calling the Product Constructor everything is correct on the book but i cant get it right, this is the find Product Constructor and my Product class.

Find product

  public Product findProduct(String productname) {
    String query = "Select * FROM " + TABLE_PRODUCTS + " WHERE " +
            COLUMN_PRODUCTNAME + " = " + productname + ";";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Product product = new Product();// Cannot be applied
    if (cursor.moveToFirst()) {
        cursor.moveToFirst();
        product.setId(Integer.parseInt(cursor.getString(0)));
        product.setProductName(cursor.getString(1));
        product.setQuantity(Integer.parseInt(cursor.getString(2)));
        cursor.close();
    } else {
        product = null;
    }
    db.close();
    return product;
}

My Product Class

public class Product {
private int id;
private String ProductName;
private int Quantity;

public Product(int _id, String _productname, int _quantity) {
    this.id = _id;
    this.ProductName = _productname;
    this.Quantity = _quantity;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getProductName() {
    return ProductName;
}

public void setProductName(String productName) {
    this.ProductName = productName;
}

public int getQuantity() {
    return Quantity;
}

public void setQuantity(int quantity) {
    this.Quantity = quantity;
}

}

Thank you.


Solution

  •     public Product(int _id, String _productname, int _quantity) {
    

    is the only constructor in you Product class definition (you don't have any others), so you have to call its constructor with these 3 parameters - instead of

        Product product = new Product();// Cannot be applied
    

    use something as

        Product product = new Product(132, "Wheel", 1000);
    

    Another solution:

    Add another constructor in your Product class besides existing one, e. g. an empty one:

        public Product() {}
    

    (it may be located before or after your existing one).