I'm new to this so please forgive me if I tagged something incorrectly or left something out.
I'm writing a java program (new to java also) - the purpose of the program is to generate an XML file with information from multiple databases.
The setup - I have sql.java which is the main class and has the main method. Sql.java calls methods located in the CCReturns.java class, GBLRets.java class, and CWSReturns.java class. Each method returns a string of XML containing pertinent information and then the main method in sql.java puts them all together in one string and creates an xml file.
Problem: One of my methods in CWSReturns should return a resultset containing 74 rows in all but is only returning the data from one of the rows. When I put this same code into the sql.java main method all 74 rows are returned in the console but the xml file only shows the data from one of the rows and all of the data from all of my other methods is repeated even though I only need it to output once.
What would be the best way to go about fixing this issue? I'm stumped.
Method in CWSReturns:
public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException
{
String unitinfo = null;
//Get Connection
connection = getCWSConnection();
//Create the SQL Query and put it into a String Variable
stmt = connection.createStatement();
//Pull Policy Claim Unit Information from CLM_UNIT Table
String query = "SELECT CLUT.UNIT_TYPE AS CLUNITTYPE, CLUT.UNIT_SUBTYPE AS CLUNITSUBTYPE, CLUT.UNIT_CATEGORY AS CLUNITCATEGORY, CLUT.UNIT_IDENTIFIER AS CLUNITIDENTIFIER, CLUT.UNIT_NUM AS CLUNITNUM, " +
"CLUT.YEAR AS CLUNITYEAR, CLUT.MAKE AS CLMAKE, CLUT.MODEL AS CLMODEL, CLUT.VEHICLE_ID AS CLVEHICLEID, CLUT.ITEM_DESC1 AS CLITEMDESC1, CLUT.LICENSE, " +
"DAM.LOCATION1, DAM.DESC1, " +
"UNT.UNIT_TYPE, UNT.UNIT_SUB_TYPE, UNT.UNIT_CATEGORY, UNT.UNIT_IDENTIFIER, UNT.UNIT_NUM, UNT.YEAR, UNT.MAKE, UNT.MODEL, UNT.VEHICLE_ID, UNT.LICENSE, UNT.ITEM_DESC, " +
//Pull Coverage Information from POL_COVERAGE Table
"COV.COVERAGE_TYPE, COV.DED_TYPE_CODE1, COV.DEDUCTIBLE1, COV.DED_TYPE_CODE2, COV.DEDUCTIBLE2, COV.DED_TYPE_CODE3, COV.DEDUCTIBLE3, COV.LIMIT_TYPE1, COV.LIMIT1, " +
"COV.LIMIT_TYPE2, COV.LIMIT2, COV.LIMIT_TYPE3, COV.LIMIT3, COV.LIMIT_TYPE4, COV.LIMIT4 " +
"FROM DB2ADMIN.CLM_CLAIM CLM, DB2ADMIN.CLM_UNIT CLUT, DB2ADMIN.POL_GENERAL_REC POL, DB2ADMIN.POL_UNIT UNT, DB2ADMIN.POL_COVERAGE COV, DB2ADMIN.CLM_DAMAGE DAM " +
"WHERE CLM.CLAIM_ID = CLUT.CLAIM_ID AND CLM.POLICY_ID = POL.POLICY_ID AND POL.POLICY_ID = UNT.POLICY_ID AND UNT.POL_UNIT_ID = COV.POL_UNIT_ID AND CLUT.UNIT_ID = DAM.UNIT_ID " +
"AND CLM.CLAIM_ID = 14701";
//Execute the query and save it as a ResultSet
rs = stmt.executeQuery(query);
//Pull out all of the information and save it as a string
while(rs.next())
{
//Retrieve by column name
//Claim Unit Info
String CL_UNIT_YEAR = "<CL_UNIT_YEAR>" + rs.getString("CLUNITYEAR") + "</CL_UNIT_YEAR>\n";
String CL_UNIT_TYPE = "<CL_UNIT_TYPE>" + rs.getString("CLUNITTYPE") + "</CL_UNIT_TYPE>\n";
String CL_UNIT_SUB_TYPE = "<CL_UNIT_SUB_TYPE>" + rs.getString("CLUNITSUBTYPE") + "</CL_UNIT_SUB_TYPE>\n";
String CL_UNIT_CATEGORY = "<CL_UNIT_CATEGORY>" + rs.getString("CLUNITCATEGORY") + "</CL_UNIT_CATEGORY>\n";
String CL_UNIT_IDENTIFIER = "<CL_UNIT_IDENTIFIER>" + rs.getString("CLUNITIDENTIFIER") + "</CL_UNIT_IDENTIFIER>\n";
String CL_UNIT_NUM = "<CL_UNIT_NUM>" + rs.getString("CLUNITNUM") + "</CL_UNIT_NUM>\n";
String CL_UNIT_MAKE = "<CL_UNIT_MAKE>" + rs.getString("CLMAKE") + "</CL_UNIT_MAKE>\n";
String CL_UNIT_MODEL = "<CL_UNIT_MODEL>" + rs.getString("CLMODEL") + "</CL_UNIT_MODEL>\n";
String CL_UNIT_VEH_ID = "<CL_UNIT_VEH_ID>" + rs.getString("CLVEHICLEID") + "</CL_UNIT_VEH_ID>\n";
String CL_UNIT_DESC1 = "<CL_UNIT_DESC1>" + rs.getString("CLITEMDESC1") + "</CL_UNIT_DESC1>\n";
String TAG_NUMBER = "<TAG_NUMBER>" + rs.getString("LICENSE") + "</TAG_NUMBER>\n";
String DAMLOC = "<DAMAGE_LOCATION>" + rs.getString("LOCATION1") + "</DAMAGE_LOCATION>\n";
String DAMDESC = "<DAMAGE_DESCRIPTION>" + rs.getString("DESC1") + "</DAMAGE_DESCRIPTION>\n";
String UNIT_TYPE = "<UNIT_TYPE>" + rs.getString("UNIT_TYPE") + "</UNIT_TYPE>\n";
String UNIT_SUB_TYPE = "<UNIT_SUB_TYPE>" + rs.getString("UNIT_SUB_TYPE") + "</UNIT_SUB_TYPE>\n";
String UNIT_CATEGORY = "<UNIT_CATEGORY>" + rs.getString("UNIT_CATEGORY") + "</UNIT_CATEGORY>\n";
String UNIT_IDENTIFIER = "<UNIT_IDENTIFIER>" + rs.getString("UNIT_IDENTIFIER") + "</UNIT_IDENTIFIER>\n";
String UNIT_NUMBER = "<UNIT_NUMBER>" + rs.getString("UNIT_NUM") + "</UNIT_NUMBER>\n";
String UNIT_YEAR = "<UNIT_YEAR>" + rs.getString("YEAR") + "</UNIT_YEAR>\n";
String UNIT_MAKE = "<UNIT_MAKE>" + rs.getString("MAKE") + "</UNIT_MAKE>\n";
String UNIT_MODEL = "<UNIT_MODEL>" + rs.getString("MODEL") + "</UNIT_MODEL>\n";
String VEH_ID = "<VEH_ID>" + rs.getString("VEHICLE_ID") + "</VEH_ID>\n";
String ITEM_DESC = "<ITEM_DESC>" + rs.getString("ITEM_DESC") + "</ITEM_DESC>\n";
//Coverage Info
String COVERAGE_TYPE = "<COVERAGE_TYPE>" + rs.getString("COVERAGE_TYPE") + "</COVERAGE_TYPE>\n";
String DED_TYPE_CODE1 = "<DED_TYPE_CODE1>" + rs.getString("DED_TYPE_CODE1") + "</DED_TYPE_CODE1>\n";
String DEDUCTIBLE1 = "<DEDUCTIBLE1>" + rs.getString("DEDUCTIBLE1") + "</DEDUCTIBLE1>\n";
String DED_TYPE_CODE2 = "<DED_TYPE_CODE2>" + rs.getString("DED_TYPE_CODE2") + "</DED_TYPE_CODE2>\n";
String DEDUCTIBLE2 = "<DEDUCTIBLE2>" + rs.getString("DEDUCTIBLE2") + "</DEDUCTIBLE2>\n";
String DED_TYPE_CODE3 = "<DED_TYPE_CODE3>" + rs.getString("DED_TYPE_CODE3") + "</DED_TYPE_CODE3>\n";
String DEDUCTIBLE3 = "<DEDUCTIBLE3>" + rs.getString("DEDUCTIBLE3") + "</DEDUCTIBLE3>\n";
String LIMIT_TYPE1 = "<LIMIT_TYPE1>" + rs.getString("LIMIT_TYPE1") + "</LIMIT_TYPE1>\n";
String LIMIT1 = "<LIMIT1>" + rs.getString("LIMIT1") + "</LIMIT1>\n";
String LIMIT_TYPE2 = "<LIMIT_TYPE2>" + rs.getString("LIMIT_TYPE2") + "</LIMIT_TYPE2>\n";
String LIMIT2 = "<LIMIT2>" + rs.getString("LIMIT2") + "</LIMIT2>\n";
String LIMIT_TYPE3 = "<LIMIT_TYPE3>" + rs.getString("LIMIT_TYPE3") + "</LIMIT_TYPE3>\n";
String LIMIT3 = "<LIMIT3>" + rs.getString("LIMIT3") + "</LIMIT3>\n";
String LIMIT_TYPE4 = "<LIMIT_TYPE4>" + rs.getString("LIMIT_TYPE4") + "</LIMIT_TYPE4>\n";
String LIMIT4 = "<LIMIT4>" + rs.getString("LIMIT4") + "</LIMIT4>\n";
//Create one large string that incorporates all of the above nodes
String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER +
CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC +
UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE +
UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 +
DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 +
LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4;
return unitinfo1;
}
stmt.close();
rs.close();
connection.close();
return unitinfo;
}
sql.java - main method snippet:
//Get unit info
String unitinfo = CWSReturns.getUnitInfo(connection, stmt, rs);
String xmlStr = (Root+mainclaimnode+mainclaiminfo+lossState+clientname+clientaddress+communicationinfo+agentname+adjustername+secondaryclientname+policyinfo+cancelpendinginfo+endmainclaimnode+claimunitnode+unitinfo+OIPName+OIPAddress+rollinjuryinfo+unitaddress+endclaimunitnode+EndRoot);
Document doc = convertStringToDocument(xmlStr);
String str = convertDocumentToString(doc);
System.out.println(str);
PrintWriter writer = new PrintWriter("C:\\Temp\\TestXML.xml");
writer.println(str);
writer.close();
Output when running method from CWSReturns (only one resultset returned...)
<CWS_XML>
<MAIN_CLAIM_INFO>
<CLAIM_ID>14701</CLAIM_ID>
<DATE_LOSS>2013-09-01 04:00:00.0</DATE_LOSS>
<CLAIM_MADE_DATE>null</CLAIM_MADE_DATE>
<CALLER_NAME>asdf asdf</CALLER_NAME>
<ACTUAL_NOT_DATE>2014-02-25 10:25:00.0</ACTUAL_NOT_DATE>
<METHOD_REPORT>PHONE</METHOD_REPORT>
<NAME_TYPE_FLAG>I</NAME_TYPE_FLAG>
<NAME_TYPE>null</NAME_TYPE>
<NAME_PREFIX>null</NAME_PREFIX>
<LAST_NAME>Luke</LAST_NAME>
<NAME_SUFFIX>null</NAME_SUFFIX>
</MAIN_CLAIM_INFO>
**<CLAIM_UNIT_INFO>
<CL_UNIT_YEAR>2014</CL_UNIT_YEAR>
<CL_UNIT_TYPE>DRIVE_OTHR</CL_UNIT_TYPE>
<CL_UNIT_SUB_TYPE>COMBO</CL_UNIT_SUB_TYPE>
<CL_UNIT_CATEGORY>DRIVE_OTHR</CL_UNIT_CATEGORY>
<CL_UNIT_IDENTIFIER>2014 Cadillac</CL_UNIT_IDENTIFIER>
<CL_UNIT_NUM/>
<CL_UNIT_MAKE>Cadillac </CL_UNIT_MAKE>
<CL_UNIT_MODEL/>
<CL_UNIT_VEH_ID/>
<CL_UNIT_DESC1>null</CL_UNIT_DESC1>
<TAG_NUMBER/>
<DAMAGE_LOCATION>Unknown</DAMAGE_LOCATION>
<DAMAGE_DESCRIPTION>Unknown</DAMAGE_DESCRIPTION>
<UNIT_TYPE>NON_OWNED</UNIT_TYPE>
<UNIT_SUB_TYPE>COMBO</UNIT_SUB_TYPE>
<UNIT_CATEGORY>NON_OWNED</UNIT_CATEGORY>
<UNIT_IDENTIFIER>NON OWNED</UNIT_IDENTIFIER>
<UNIT_NUMBER>null</UNIT_NUMBER>
<UNIT_YEAR>null</UNIT_YEAR>
<UNIT_MAKE>null</UNIT_MAKE>
<UNIT_MODEL>null</UNIT_MODEL>
<VEH_ID>null</VEH_ID>
<ITEM_DESC>null</ITEM_DESC>
<COVERAGE_TYPE>ADB</COVERAGE_TYPE>
<DED_TYPE_CODE1>null</DED_TYPE_CODE1>
<DEDUCTIBLE1>null</DEDUCTIBLE1>
<DED_TYPE_CODE2>null</DED_TYPE_CODE2>
<DEDUCTIBLE2>null</DEDUCTIBLE2>
<DED_TYPE_CODE3>null</DED_TYPE_CODE3>
<DEDUCTIBLE3>null</DEDUCTIBLE3>
<LIMIT_TYPE1>LIM</LIMIT_TYPE1>
<LIMIT1>15000.000</LIMIT1>
<LIMIT_TYPE2>null</LIMIT_TYPE2>
<LIMIT2>null</LIMIT2>
<LIMIT_TYPE3>null</LIMIT_TYPE3>
<LIMIT3>null</LIMIT3>
<LIMIT_TYPE4>null</LIMIT_TYPE4>
<LIMIT4>null</LIMIT4>
<OIP_NAME>Null</OIP_NAME>
<OIP_ADDR>Null</OIP_ADDR>
<ROLE_TYPE>DRIVER</ROLE_TYPE>
<INJURY_TEXT>head</INJURY_TEXT>
<CL_UNIT_ID>Null</CL_UNIT_ID>
<CL_UNIT_HOUSE>Null</CL_UNIT_HOUSE>
<CL_UNIT_ADDR1>Null</CL_UNIT_ADDR1>
<CL_UNIT_ADDR2>Null</CL_UNIT_ADDR2>
<CL_UNIT_CITY>Null</CL_UNIT_CITY>
<CL_UNIT_STATE>Null</CL_UNIT_STATE>
<CL_UNIT_ZIP>Null</CL_UNIT_ZIP>
</CLAIM_UNIT_INFO>**
</CWS_XML>
The elements in the "CLAIM_UNIT_INFO" node should repeat upwards of 74 times...
Inside the while loop you are returning. So it iterates only one time.
Make unitinfo in getUnitInfo() method as a StringBuilder and inside the while(rs.next) instead or returning append the unitinfo1 to unitinfo
public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException
{
StringBuilder unitinfo = new StringBuilder();
...
while(rs.next()) {
...
unitinfo.append("<CLAIM_UNIT_INFO>");
//Create one large string that incorporates all of the above nodes
String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER +
CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC +
UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE +
UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 +
DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 +
LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4;
unitinfo.append(unitinfo1);
unitinfo.append("</CLAIM_UNIT_INFO>");
}
...
return unitinfo.toString();
}
As #SyamS mentioned you are returning inside of your loop.
If you don't want to combine all of the rows into one String: One way to fix this would be to store the String found in the loop into an ArrayList, and then return the ArrayList of String.
You would have to change the return type of your method, and handle iterating through the resulting ArrayList when you called the method.
public static ArrayList<String> getUnitInfo(...){
ArrayList<String> unitinfo = new ArrayList<String>();
...
while(...){
...
unitinfo.add(unitinfo1); // Instead of return
}
...
return unitinfo; // Only return at the end
}
The reason this is happening is because you have return unitinfo1 inside your while loop. So it is just returning after the first row has been populated.
You need to declare String unitinfo1 outside of the while loop, and append each line to the string during each iteration of the loop.
String unitinfo1;
while(condition)
{
unitinfo1.append(nextLine);
}
return unitinfo1;
Related
I'm using RecyclerView I have an Activity that queries my database and I insert this data into that ArrayList , and I want to list that data in another Activity.
This is where I query and add the data to the ArrayList
String queryProduto = "SELECT" +
" Produto_Servico.ID, Produto_Servico.Descricao," +
" Produto_Estoque.EstoqueAtual, ValorVenda" +
" FROM" +
" Produto_Valor" +
" INNER JOIN" +
" Produto_Servico" +
" ON" +
" Produto_Servico.ID = Produto_Valor.ID_Produto" +
" INNER JOIN" +
" Produto_Estoque" +
" ON" +
" Produto_Estoque.ID_Produto = Produto_Servico.ID" +
" WHERE" +
" Produto_Estoque.EstoqueAtual > 0" +
" ORDER BY" +
" Produto_Servico.Descricao";
Statement stmtP = connect.createStatement();
ResultSet rsP = stmtP.executeQuery(queryProduto);
String queryPessoa = "SELECT ID_Pessoa FROM Novo_Pedido";
Statement stmtPS = connect.createStatement();
ResultSet rsPS = stmtPS.executeQuery(queryPessoa);
while (rsPS.next()){
cod = rsPS.getString("ID_Pessoa");
}
if (rsP != null) {
while (rsP.next()) {
id = String.valueOf(rsP.getString("ID"));
desc = rsP.getString("Descricao");
estoque = String.valueOf(rsP.getString("EstoqueAtual"));
valorDec = rsP.getBigDecimal(4);
qtdStr = String.valueOf(qtd);
valorStr = decimalFormat.format(valorDec);
String descFinal = desc;
String qtdFinal = qtdStr;
final BigDecimal[] valorFinal = {valorDec};
try {
listProdutosPedidosFinalizar.add(new ListProdutosPedidosFinalizar(descFinal, qtdFinal, valorFinal[0], BigDecimal.ZERO));
classeLists.setListProdutosPedidosFinalizar(listProdutosPedidosFinalizar);
produtosPedidosAdapter = new ProdutosPedidosAdapter(listProdutosPedidos, this, new ProdutosPedidosAdapter.OnClickListener() {
/*METHODS*/
produtosPedidosAdapter.notifyDataSetChanged();
listProdutosPedidos.add(new ListProdutosPedidos(id, desc, estoque, valorStr, qtdStr));
} catch (Exception ex) {
ex.printStackTrace();
}
rvProdutosPedidos.setAdapter(produtosPedidosAdapter);
produtosPedidosAdapter.notifyDataSetChanged();
isSuccess = true;
}
And now I want to list the listProdutosPedidos data in another Activity.
Define listProdutosPedidos list as static member of your class and then use className.listProdutosPedidos code to access records in it.
I would like to print the values of an object from DAO to servlet.
DAO:
public static List getFree(String svLectID,String ExLectID) throws SQLException, ClassNotFoundException
{
currentCon = JavaConnectionDB.getConnection() ;
PreparedStatement ps1 = currentCon.prepareStatement("SELECT *\n" +
"FROM (\n" +
" SELECT e1.FreeID,\n" +
" e1.lecturerID SVID,\n" +
" e1.availableID SVavail,\n" +
" e1.freedate AS SVFree,\n" +
" e2.lecturerID AS Examiner, \n" +
" e2.freedate EXFree,\n" +
" s.studentID,\n" +
" s.studentName,\n" +
" s.lecturerID AS lectID,\n" +
" sv.lecturerID AS SVlecturerID,\n" +
" sv.lecturerFullname AS SVlecturerName,\n" +
" ex.lecturerID AS EXlecturerID,\n" +
" ex.lecturerFullname AS EXlecturerName,\n" +
" v.availableID availID,\n" +
" v.availableDay,\n" +
" v.availableStart,\n" +
" v.availableEnd,\n" +
" ROW_NUMBER() OVER (PARTITION BY e1.lecturerID \n" +
" ORDER BY dbms_random.random) AS rn\n" +
" FROM free e1 \n" +
" INNER JOIN free e2 \n" +
" ON e1.availableID = e2.availableID\n" +
" INNER JOIN student s\n" +
" ON s.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer sv\n" +
" ON sv.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer ex\n" +
" ON ex.lecturerID = e2.lecturerID\n" +
" INNER JOIN availability v\n" +
" ON v.availableID = e2.availableID\n" +
" \n" +
" \n" +
" WHERE e1.lecturerID = ? \n" +
" AND e2.lecturerID = ? \n" +
" ORDER BY e2.availableID asc\n" +
" \n" +
" )\n" +
"WHERE rn <=5") ;
ps1.setString(1, svLectID) ;
ps1.setString(2, ExLectID);
List list = new ArrayList() ;
ResultSet rs1 = ps1.executeQuery() ;
while(rs1.next())
{
Object[] obj = new Object[17] ;
obj[0] = rs1.getString(1) ;
obj[1] = rs1.getString(2);
obj[2] = rs1.getInt(3);
obj[3] = rs1.getDate(4);
obj[4] = rs1.getString(5);
obj[5] = rs1.getDate(6);
obj[6] = rs1.getString(7);
obj[7] = rs1.getString(8);
obj[8] = rs1.getString(9);
obj[9] = rs1.getString(10);
obj[10] = rs1.getString(11);
obj[11] = rs1.getString(12);
obj[12] = rs1.getString(13);
obj[13] = rs1.getInt(14);
obj[14] = rs1.getString(15);
obj[15] = rs1.getDate(16);
obj[16] = rs1.getDate(17);
list.add(obj) ;
System.out.println("zabir "+rs1.getString(8));
}
return list ;
}
As you can see these values are stored in an object into a list. I retrieve these values to servlet.
SERVLET:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
currentCon = JavaConnectionDB.getConnection();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext context=getServletContext();
String[] studentID = request.getParameterValues("studentID");
String[] supervisorID = request.getParameterValues("supervisorID");
String[] examinerID = request.getParameterValues("examinerID");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try{
out.println("<br><center><table><tr>"
+ "<th>Student Name</th>"
+ "<th>Project Title</th>"
+ "<th>Supervisor Name</th>"
+ "<th>Examiner Name</th>"
+ "<th>Start</th>"
+ "<th>End</th>"
+ "<th>Date</th>"
+ "</tr>");
for (int i=0 ; i<studentID.length ; i++){
FreeBean free = new FreeBean();
PresentationBean present = new PresentationBean();
StudentBean student = new StudentBean();
List list = new ArrayList() ;
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
out.println("<tr>");
out.println("<tr>");
out.println("<td>"+ studentID[i]+"</td>");
out.println("<td> Hello </td>");
out.println("<td>"+ supervisorID[i] +"</td>");
out.println("<td>"+ examinerID[i] +"</td>");
out.println("<td>"+ SVavailableID+"</td>");
out.println("<td>"+ EXavailableID+"</td>");
out.println("<td>"+ EXFreeDate+"</td>");
out.println("</tr>");
}//student loop
out.println("</center></table><br><br>");
out.println("</body>");
out.println("</html>");
}// first try
catch (Exception e)
{
e.printStackTrace() ;
}//first catch
}//throws method
I tried to get the value using SOP first like this:
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
First SOP produce : [Ljava.lang.Object;#13432ad
Second SOP produce : [[Ljava.lang.Object;#1dd079f,
My first assumption was get(0) wil give me FreeID value. As declared in DAO.
So how can i get the value if using get(0) is wrong?
Your freeId should be in the first position of each array present in the list returned by the method getFree.
To get the freeId of the first element of the list you should do something like:
System.out.println((Object[]) list.get(0))[0]);
For the freeId of the second element of the list:
System.out.println((Object[]) list.get(1))[0]);
and so on.
It will be more readable doing something like that:
Object[] firstObjectAsArray = (Object[]) list.get(0);
System.out.println(firstObjectAsArray[0]);
Object[] secondObjectAsArray = (Object[]) list.get(1);
System.out.println(secondObjectAsArray[0]);
To print the freeId of all elements of the list
for (Object objectAsArray : list) {
System.out.println(((Object[]) objectAsArray)[0]);
}
Note: looking at your code there is a not necessary creation of an empty list. The code:
List list = new ArrayList() ; // Not necessary
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
can be optimized as follow:
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
List list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
Note: using generics you don't need the cast. To do that replace the definition of the list
List list = new ArrayList();
with
List<Object[]> list = new ArrayList<Object[]>();
Your list contains arrays of Object, so you have to call the relevant indexes of the array.
You could debug the full list like this
// iterate over the list
for (int i = 0; i < list.size(); i++) {
Object[] array = (Object[])(list.get(i));
// iterate over the Object array
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
}
}
I am building a tag reader for inventory purpose. Using the for loop to iterate through the tags to count/total the ids. I get an error on my return line "tagsFound cannot be resolved into a variable". How do i use the variable inside the for loop and then access it outside the loop?
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
for (int i=0; i<tagList.length; i++) {
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
String[] tagsFound;
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
String[] tagsFound = new String[tagList.length];
for (int i=0; i<tagList.length; i++) {
tagsFound = "";
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
the returned array will have empty strings in the positions where the tag does not satisfy the criteria.
I need to import csv into access database using java. I tried using the following code
my code:
public static void main (String args[])
{
String dbFileSpec = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\Centre.accdb";
// String accessTableName = "Centre";
String csvDirPath = "C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase";
String csvFileName = "myjdbcfile.csv";
try (Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://" + dbFileSpec
// + ";newdatabaseversion=V2007"
)) {
try
{
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
System.err.println("SQL --> "+strSQL);
PreparedStatement selectPrepSt = conn.prepareStatement(strSQL);
boolean result = selectPrepSt.execute();
System.out.println("result = " + result);
}
catch(SQLException ex)
{
System.err.println("Error --->"+ex.toString());
}
conn.commit();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But it throws error as "net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: INTO required: FROM".
The two problems with trying to use
SELECT ... INTO NewTableName FROM [Text; ...].[csvFileName]
in this context are:
SELECT ... INTO NewTableName FROM OldTableName is an Access SQL construct that UCanAccess does not support (at least not at the moment), and
... FROM [Text; ...].[csvFileName] is an ODBC "trick" and UCanAccess does not use ODBC.
However, UCanAccess uses HSQLDB and HSQLDB offers support for reading CSV files like so:
final String csvFolder = "C:/__tmp/zzzTest/";
final String csvFileName = "myjdbcfile.csv";
final String csvDbName = "hsqldbTemp";
try (Connection hconn = DriverManager.getConnection(
"jdbc:hsqldb:file:" + csvFolder + "/" + csvDbName,
"SA",
"")) {
try (Statement s = hconn.createStatement()) {
s.executeUpdate("CREATE TEXT TABLE fromcsv (id int, textcol varchar(50))");
s.executeUpdate("SET TABLE fromcsv SOURCE \"" + csvFileName + "\" DESC");
try (ResultSet rs = s.executeQuery("SELECT * FROM fromcsv")) {
while (rs.next()) {
System.out.println(rs.getString("textcol"));
}
}
s.executeUpdate("SHUTDOWN");
File f = null;
f = new File(csvFolder + "/" + csvDbName + ".properties");
f.delete();
f = new File(csvFolder + "/" + csvDbName + ".script");
f.delete();
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
so you could use two connections,
one jdbc:ucanaccess connection to the Access database, and
another jdbc:hsqldb connection to the CSV file,
and then insert the rows from the CSV file into a table in the Access database.
You have mis-typed the query here,
String strSQL = "SELECT * INTO " + dbFileSpec + " FROM
[Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
should be ,
String strSQL = "SELECT *" + dbFileSpec + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";
I'm trying to populate Hashmap as following:
public static final String KEY_PROPNAME = "";
public static final String KEY_KEYWORDS = "";
public static final String KEY_THUMB_URI = "";
ArrayList<HashMap<String, String>> clipsList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < clipDetailsArr.length; i = i
+ constants.noOfColumns) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_PROPNAME, clipDetailsArr[i]);
map.put(KEY_PROPTYPE, clipDetailsArr[i + 1]);
map.put(KEY_PRICE, clipDetailsArr[i + 2]);
map.put(KEY_LOCATION, clipDetailsArr[i + 3]);
map.put(KEY_SQFT, clipDetailsArr[i + 4]);
map.put(KEY_SQFTTYPE, clipDetailsArr[i + 5]);
map.put(KEY_BED, clipDetailsArr[i + 6]);
map.put(KEY_BATH, clipDetailsArr[i + 7]);
map.put(KEY_KEYWORDS, clipDetailsArr[i + 8]);
map.put(KEY_THUMB_URI, clipDetailsArr[i + 9]);
Log.i("Main", "Clip clipDetailsArr[]: 0=" + clipDetailsArr[i] + " ,1=" + clipDetailsArr[i + 1]
+ " ,2=" + clipDetailsArr[i + 2] + " ,3=" + clipDetailsArr[i + 3] + " ,4="
+ clipDetailsArr[i + 4] + " ,5=" + clipDetailsArr[i + 5] + " ,6="
+ clipDetailsArr[i + 6] + " ,7=" + clipDetailsArr[i + 7] + " ,8="
+ clipDetailsArr[i + 8] + " ,9=" + clipDetailsArr[i + 9]);
Log.i("Main", "Clip PROPNAME=" + MainActivity.KEY_PROPNAME
+ " ,KEYWORDS" + MainActivity.KEY_KEYWORDS + " ,URI="
+ MainActivity.KEY_THUMB_URI);
Log.i("Main", "Clip get PROPNAME=" + map.get(KEY_PROPNAME)
+ " ,KEYWORDS" + map.get(KEY_KEYWORDS) + " ,URI="
+ map.get(KEY_THUMB_URI));
clipsList.add(map);
}
Output of log is something like this:
Clip clipDetailsArr[]: 0=Opt out ,1=Residentail ,2=10000 ,3=Andheri ,4=500 ,5=Carpet ,6=2 ,7=1 ,8=optout ,9=/mnt/sdcard/Clipping/optout.png
Clip PROPNAME= ,KEYWORDS ,URI=
Clip get PROPNAME=/mnt/sdcard/Clipping/optout.png,
KEYWORDS/mnt/sdcard/Clipping/optout.png,
URI=/mnt/sdcard/Clipping/optout.png//AND SO ON
Referring to above log, I have values in my array and I'm putting them into array by using map.put(key,value) but in 2nd log MainActivity.KEY_PROPNAME and other fields are empty. Also, when I use map.get(key), all the column have data of last column.
Note that last column data is getting populated appropriately.
Am I doing something wrong here? Any help appreciated.
You are using the same key "" for at least three .put() !! You have defined :
public static final String KEY_PROPNAME = "";
public static final String KEY_KEYWORDS = "";
public static final String KEY_THUMB_URI = "";
And then you populate the Map as :
map.put(KEY_PROPNAME, clipDetailsArr[i]);
map.put(KEY_KEYWORDS, clipDetailsArr[i + 8]);
map.put(KEY_THUMB_URI, clipDetailsArr[i + 9]);
As per the Javadoc:
If the map previously contained a mapping for the key, the old value is replaced.
public static final String KEY_PROPNAME = "";
public static final String KEY_KEYWORDS = "";
public static final String KEY_THUMB_URI = "";
Here all of your keys have same value/name, Hence all the data will store in the same key !!
public static final String KEY_PROPNAME = "";
public static final String KEY_KEYWORDS = "";
public static final String KEY_THUMB_URI = "";
This is the error, instead of creating empty strings from your name you should use them as the Keys to get your requested behavior.
Just to keep your code almost the same you could to something like:
public static final String KEY_PROPNAME = "KEY_PROPNAME";
public static final String KEY_KEYWORDS = "KEY_KEYWORDS";
public static final String KEY_THUMB_URI = "KEY_THUMB_URI";
That should to the trick even if it is a little funky ;)