What is this error? (Java database application) - java

I have the following code and I'm trying to return data from my database (itemName, itemId). Yet it gives me the following error:
Items() in Items cannot be applied to:
Expected Actual
Parameters: Arguments:
pool: com.sun.tools.javac.jvm.Pool itemName (java.lang.String)
code: com.sun.tools.javac.jvm.Code itemId (java.lang.String)
symtab: com.sun.tools.javac.code.Symtab quantity (java.lang.String)
types: com.sun.tools.javac.code.Types cost (java.lang.String)
Here is my code:
public List<Items> getItemList() throws SQLException{
try {
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Items");
{
List<Items> itemsList = new ArrayList<>();
while (results.next()) {
String itemName = String.valueOf(results.getString("item_name"));
String itemId = String.valueOf(results.getString("item_id"));
Items items = new Items(itemName, itemId); // where the error is
itemsList.add(items);
}
return itemsList;
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}
Is it because the types are incompatible (object v. string)? If so, String.valueOf... incorrect?
EDIT
public class Items {
// Constructor
public Items(String itemName, String itemId){
setItemName(itemName);
setItemId(itemId);
}
// itemName
private final StringProperty itemName = new SimpleStringProperty(this,"itemName");
public StringProperty itemNameProperty(){
return itemName;
}
public final String getItemName(){
return itemNameProperty().get();
}
public final void setItemName(String itemName){
itemNameProperty().set(itemName);
}
// itemId
private final StringProperty itemId = new SimpleStringProperty(this,"itemId");
public StringProperty itemIdProperty(){
return itemId;
}
public final String getItemId(){
return itemIdProperty().get();
}
public final void setItemId(String itemId){
itemIdProperty().set(itemId);
}
}

That looks like an issue that is caused by importing an Items class from the wrong package. If you have an import statement of the form
import some.package.name.Items ;
near the top of the class containing your first block of code, then remove that line.
If the class containing the first block of code is in a different package to your Items class, then you need to add in a line
import the.correct.package.Items ;
in place of the incorrect import statement. Replace the.correct.package with the name of the package containing your Items class (in Items.java, look at the first line of code, which is a package statement defining which package contains Items).
For some background information, I recommend Meaning of the import statement in a Java file

Related

How to set values for class array variable?

I am setting values to an API and I need to set values for class data type variable which is an array and I need to know how to set the value?
I have tried in java, and I keep on getting compile time error
Items equipmenxxts = new Items ();
equipmenxxts.setDKU(savedRequest.DKUType());
equipmenxxts.setQuantity(savedRequest.getQuantity());
item.setEquipments(equipmenxxts);
**//error setEquipments(Items[]) in ItemOrder cannot be applied to (Items)**
api class to set values
public class ItemOrder implements java.io.Serializable {
private java.lang.String company,
private Items[] equipments; // class given below
public ItemOrder() {
}
public ItemOrder(Items[] equipments) {
this.equipments = equipments;
}
public java.lang.String getCompany() {
return company;
}
public void setCompany(java.lang.String company) {
this.company = company;
}
public Items[] getEquipments() {
return equipments;
}
public void setEquipments(Items[] equipments) {
this.equipments = equipments;
}
}
data type of this class used above
public class Items implements java.io.Serializable {
private java.lang.String DKU;
private int quantity;
public Items() {
}
public Items(String DKU, int quantity) {
this.DKU = DKU;
this.quantity = quantity;
}
}
api class to set up value
#Service("clApiService")
public class NewApiImpl implements NewApiService {
#Override
public Request completeapiNewOrderRep(ServletWebRequest webRequest) {
try {
ItemOrder item = new ItemOrder();
item.setCompany(req.getCompany());
item.setEquipments(); //error setEquipments(Items[]) in ItemOrder cannot be applied to ()**
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
I expect just to set the values of (req.setDKU and Quantity) to item.setEquipments( );
.setEquipments(Items[]) demands an array of items, but you pass only a single item.
try creating an array containing your item first:
item.setEquipments(new Items[] {equipmenxxts});
Alternatively you can create equipmentxxts as an array:
final Items[] equipmenxxts = new Items[1];
equipmenxxts[0].setDKU(savedRequest.DKUType());
equipmenxxts[0].setQuantity(savedRequest.getQuantity());
item.setEquipments(equipmenxxts);
Also, when setting a number of items this way, make sure you do not expose your class' internal state, unless you really know what you are doing—and why! You may consider a variable number of arguments for your method:
public Items[] getEquipments() {
return Arrays.copyOf(equipments, equipments.length);
}
public void setEquipments(Items... equipments) {
this.equipments = Arrays.copyOf(equipments, equipments.length);
}
Now you can either call .setEquipments(...) with an array as parameter, or with a custom number of items:
item.setEquipments(e1, e2, e3);
You may reconsider the names of your variables. I do not understand, why an ItemOrder object is called "item" - and you set "Items" objects through .setEquipments(...)
For what I studied, making a set for an array is somewhat a design error. You can, however, make a void setItems(Items i), introducing on parameters a certain index of an ItemOrder or you can make a "superset", which is not a real set:
public void superSet(ItemOrder io){
this.equipments=io.setEquipments(Items[] i);
}

get several method's return values from a class in one statement

Item searchByPattern(String pat)
{
for(Iterator iter = items.iterator(); iter.hasNext(); )
{
Item item = (Item)iter.next();
if ((xxxxxxxxxxxx).matches(".*"+pat+".*"))
{
return item;
}
}
}
The above code is part of a class from my java program
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
/**
* Initialise the fields of the item.
*/
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = true;
comment = "";
}
public String getTitle() {
return title;
}
/**
* Enter a comment for this item.
*/
public void setComment(String comment)
{
this.comment = comment;
}
/**
* Return the comment for this item.
*/
public String getComment()
{
return comment;
}
/**
* Set the flag indicating whether we own this item.
*/
public void setOwn(boolean ownIt)
{
gotIt = ownIt;
}
/**
* Return information whether we own a copy of this item.
*/
public boolean getOwn()
{
return gotIt;
}
public int getPlayingTime()
{
return playingTime;
}
/**
* Print details about this item to the text terminal.
*/
public void print()
{
System.out.println("Title: " + title);
if(gotIt) {
System.out.println("Got it: Yes");
} else {
System.out.println("Got it: No");
}
System.out.println("Playing time: " + playingTime);
System.out.println("Comment: " + comment);
}
}
I want to access all the methods that return values from class Item and once it matches the statement in Item searchByPattern, it will return the object.
I knew that I can do it by or operator like item.getTitle().matches(".*"+pat+".*") ||item.getComment().matches(".*"+pat+".*")||.......
but is it possible to get the same result by using a method in (xxxxxxxxxx)?
This isn't directly possible to do, however there are a few things you can try (from easiest to hard):
Just check all String type methods yourself in your code.
Add a special method in Item that does the match so Item class can decide itself when it matches. Here again you will need to make check all Strings manually.
You could add a method to Item that returns all methods that return a String as functions:
Code:
List<Supplier<String>> getAllStringMethods() {
return Arrays.asList(this::getComment, this::getTitle);
}
You can then use that to check all Strings one at a time by doing:
boolean match = item.getAllStrings().stream()
.map(Supplier::get)
.anyMatch(s -> s.matches("pattern"));
You can use Reflection to inspect the Item.class to find all methods that take no parameters and return a String, and then invoke them one by one. This is complicated and slow, and beyond the scope of this answer to explain further.

How to fill a report by passing parameters? (JAVA/Jasper Reports)

I created the following report from an Access database:
This only use two parameters: $P{Image} (for set my resource icon) and $P{Cedula} (for WHERE clause). In Jaspersoft Studio works perfect... I already knew from the beginning that the biggest challenge would be to call this report from java.
I read some questions from this site and here. In VB.NET currently I do something similar to the last page (data source from a class) with reportViewer, so I made the following class:
package DataBeans;
public class Paciente {
private String nombre,apellido,cedula;
private String fecha_nacimiento,sexo,tipo_sangre;
private String direccion,telefono;
public void setNombre(String v){nombre=v;}
public void setApellido(String v){apellido=v;}
public void setCedula(String v){cedula=v;}
public void setFechaNacimiento(String v){fecha_nacimiento=v;}
public void setSexo(String v){sexo=v;}
public void setTipoSangre(String v){tipo_sangre=v;}
public void setDireccion(String v){direccion=v;}
public void setTelefono(String v){telefono=v;}
public String getNombre(){return nombre;}
public String getApellido(){return apellido;}
public String getCedula(){return cedula;}
public String getFechaNacimiento(){return fecha_nacimiento;}
public String getSexo(){return sexo;}
public String getTipoSangre(){return tipo_sangre;}
public String getDireccion(){return direccion;}
public String getTelefono(){return telefono;}
}
And the class "DataBeans", like the site:
package DataBeans;
import Clases.Administrador;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class DataBeans {
public ArrayList<Paciente> getPacientes(String[] values) throws ClassNotFoundException, SQLException{
Administrador admin = new Administrador();
ArrayList<Paciente> ListaPacientes = new ArrayList<>();
ResultSet rs = admin.SelectParametrizado(values, "SELECT * FROM Pacientes WHERE Cedula=?");
while(rs.next()){
ListaPacientes.add(producirPaciente(rs.getString("Nombre"), rs.getString("Apellido"), rs.getString("Cedula")
,rs.getString("Fecha_Nacimiento"),rs.getString("Sexo"),rs.getString("Tipo_Sangre")
,rs.getString("Direccion"),rs.getString("Telefono")));
}
return ListaPacientes;
}
public Paciente producirPaciente(String n, String a, String c, String fn, String s, String ts, String d, String t){
Paciente pac = new Paciente();
pac.setNombre(n);
pac.setApellido(a);
pac.setCedula(c);
pac.setFechaNacimiento(fn);
pac.setSexo(s);
pac.setTipoSangre(ts);
pac.setDireccion(d);
pac.setTelefono(t);
return pac;
}
}
I think my intentions are clearly reflected what I try to achieve with the code of both classes. The Function "SelectParametrizado" (parameterizedSelect) returns me a ResultSet that I use to fill data to each element of arrayList (ListaPacientes). I want to use that ArrayList like a DataSource for my report.
I think actually this question will be double .... for the following reason:
With this code
private JasperPrint impresion;
private JasperReport reporte;
private JRViewer reportViewer;
private JRBeanCollectionDataSource data;
private HashMap<String,Object> parametros;
private String[] values;
private DataBeans beans;
values = new String[1];
values[0] = "3-333-3333";
beans = new DataBeans();
data = new JRBeanCollectionDataSource(beans.getPacientes(values));
parametros = new HashMap<>();
reporte = (JasperReport) JRLoader.loadObject(new File("Reportes/PerfilPaciente.jasper"));
impresion = JasperFillManager.fillReport(reporte,parametros,data);
reportViewer = new JRViewer(impresion);
I get the following error...
Probably, you will think something like "yes, because you didnt set the Image parameter", but that is not working too...
data = new JRBeanCollectionDataSource(beans.getPacientes(values));
parametros = new HashMap<>();
**parametros.put("Imagen", ClassLoader.getSystemResource("perfil-azul.png").getPath());**
reporte = (JasperReport) JRLoader.loadObject(new File("Reportes/PerfilPaciente.jasper"));
impresion = JasperFillManager.fillReport(reporte, parametros,data);
reportViewer = new JRViewer(impresion);
I get "null-pointerException"..
How I can achieve: Loading a dataset from an arraylist and set one Image parameter for my report...?
If you know another way, feel free to comment it here... Be assured that It will be of tremendous help.

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));

class objects does not get saved in parse databrowser android

I have started with parse to store the data of my class. I have followed parse guide and tutorials and tried to implement the code. Unfortunately, the objects of class are not getting saved in parse data browser. When I see the data in browser just one object id is shown not the columns of name, desc and qty of my item class. I have created class in dashboard also created columns respective to my data. Unable to get the solution as I am new to android and parse.
Here is my code
Item class
package com.example.owner.newstock;
import com.parse.ParseClassName;
import com.parse.ParseObject;
#ParseClassName("Item")
public class Item extends ParseObject {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id, String item_name, String item_desc, String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name, String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return getString(item_name);
}
public void setItem_name(String item_name)
{
put("item_name", item_name);
}
public String getItem_desc()
{
return getString(item_desc);
}
public void setItem_desc(String item_desc)
{
put("item_desc", item_desc);
}
public String getItem_qty()
{
return getString (item_qty);
}
public void setItem_qty(String item_qty){
put("item_qty", item_qty);
}
}
code of parse in main activity
ParseObject.registerSubclass(Item.class);
Parse.initialize(this, "Kw0dyUgLoqv24QdLE30mvFBVclEzLHRGtR2hQVHA", "5BWc3bAd60EgqU0sFIj31mMYYg7OIX9WKgC0a6oP");
ParseAnalytics.trackAppOpened(getIntent());
code to save the objects
Item i = new Item();
i.setItem_name(item_name);
i.setItem_desc(item_desc);
i.setItem_qty(item_qty);
i.saveInBackground();
Am I missing something?
Rather than creating an item class that extends ParseObject, set up a ParseObject variable, as follows:
ParseObject item = new ParseObject("Item");
Then put data in as follows:
item.put("quantity", yourQuantityVariable);
item.put("description", yourDescriptionVariable);
item.put("name", yourNameVariable);
To save:
item.saveInBackground();
To retrieve data, make use of querying and the getDataType() methods. Specified on https://parse.com/docs/android/guide#objects and https://parse.com/docs/android/guide#queries

Categories

Resources