How to add field in jtable java - java

How can insert this set of code in jtable. The problem is when I do md.addElement(id); it shows me a red underline on addElement()
Here is my code
public class hospitalisation extends javax.swing.JFrame {
DefaultTableModel md = new DefaultTableModel();
public hospitalisation() {
initComponents();
hospitalisationtable.setModel(md);
buttonGroup1.add(male);
buttonGroup1.add(female);
}
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
String id = "id: " + idtxt.getText();
String name = "name: " + nametxt.getText();
String sex = "sex:";
String address = "address: " + addresstxt.getText();
String sdate = "sdate: " + sdatetxt.getText();
String room = "room: " + cs_room.getSelectedItem().toString();
String father = "father: " + fathertxt.getText();
String phone = "phone: " + phonetxt.getText();
String age = "age: " + agetxt.getText();
String edate = "edate " + edatetxt.getText();
if (female.getModel().isSelected() == true)
sex += female.getText();
else if (male.getModel().isSelected() == true)
sex += male.getText();
md.addElement(id);
md.addElement(name);
md.addElement(sex);
md.addElement(address);
md.addElement(sdate);
md.addElement(room);
md.addElement(father);
md.addElement(phone);
md.addElement(age);
md.addElement(edate);
}

it shows me a red underline on addElement()
this is because as you can see here there is no DefaultTableModel.addElement(String) in that class...
Consider instead taking a look at the doc and maybe consider one of the given methods
like
addColumn(Object columnName)
addColumn(Object columnName, Object[] columnData)
addColumn(Object columnName, Vector columnData)
addRow(Object[] rowData)
addRow(Vector rowData)

Related

error insert data in java netbeans and mysql

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}
For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}
I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

Building String name using concatenation with a for loop

I want to create a run time String name in Java.
I tried something like using in JavaScript, but it is printing value like Status_Name_0 instead Open assigned to the String Status_Name_0
public static void GetPaymentStatusList(){
int i=0;
String Status_Name_0="Open";
String Status_ID_0="0";
String Status_Name_1="Approved";
String Status_ID_1="1";
String Status_Name_2="Denied";
String Status_ID_2="2";
for(i=0; i<3; i++){
Vars.PaymentStatusName_List.add("Status_Name_"+i);
Vars.PaymentStatusId_List.add("Status_ID_"+i);
}
}
but it is printing value like Status_Name_0 instead Open
Because that's what you added to the list...
add("Status_Name_"+i);
The way to get what you want would be a Map<String, String>
Map<String, String> map = new HashMap<>();
map.put("Status_Name_0", "Open");
// ...
for (int i=0;i<map.size();i++) {
String open = map.get("Status_Name_"+i);
}
How about you make some class instead, though?
public class PaymentStatus {
int id;
String name;
public PaymentStatus(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return String.format("%s[id: %d, name: %s]",
getClass().getSimpleName(), id, name);
}
}
And a List<PaymentStatus> would be preferred over appending integers to any variables.
public static List<PaymentStatus> getPaymentStatusList() {
List<PaymentStatus> list = new ArrayList<>();
paymentStatusList.add(new PaymentStatus(0, "Open"));
paymentStatusList.add(new PaymentStatus(1, "Approved"));
paymentStatusList.add(new PaymentStatus(2, "Denied"));
return list;
}
You're actually concatenating the string "Status_name_" with "0" which would result in "Status_name_0", a string, not a variable like Status_name_0. As far as I understand, you want the values of String_name_i (i= 0, 1, 2,....). To get that working, use String array.
String[] string_names = { "Open", "Approved", "Denied" };
int[] string_id = { 0, 1, 2 };
:You may not need a string_id array, as you can use the values of i in the for loop.
And add them in the list like:
Vars.PaymentStatusName_List.add(string_name[i]);
StringBuilder param = new StringBuilder();
param.append("shopid"
+ "=" + shopDetails.getShopId() + "&" + "username" + "=" + userDetail.getUserName() + "&" + "userid" + "=" + userDetail.getUserId() + "&");
for (int i = 0; i < brandList.size(); i++) {
param.append("brandId" + "[" + i + "]" + "=" + brandList.get(i).getBrandId()
+ "&" + "shortqua" + "[" + i + "]" + "=" + shortageStockList.get(i) + "&");
}
param.append("lattude" + "=" + String.valueOf(latitude) + "&" + "longitude" + "=" + String.valueOf(longitude));

how to get string from jtable with null cell

I have jtable and the data from mysql.
In mysql I have a column that allowed for null (it's called 'fil').
When i retrive the data to jtable, it's OK.
Then, I want to fill the jtextarea and enable the button if the 'fil' is not null by click the jtable row.
Here my code:
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String num = jTable1.getValueAt(row, 0).toString();
String sub = jTable1.getValueAt(row, 1).toString();
String desc = jTable1.getValueAt(row, 2).toString();
String start = jTable1.getValueAt(row, 3).toString();
String end = jTable1.getValueAt(row, 4).toString();
String sta = jTable1.getValueAt(row, 5).toString();
String fil = jTable1.getValueAt(row, 6).toString();
if (fil != "") {
jButton1.setEnabled(true);
jButton1.setToolTipText(fil);
} else {
jButton1.setEnabled(false);
jButton1.setToolTipText("");
}
jTextArea1.setText("Subject: " + sub + "\n" + "Description: " + "\n" + desc + "\n" + "From " + start + " to " + end + "\n" + "Status: " + sta);
jLabel3.setText(num);
the problem is when I clicked the row with null 'fil', the program give the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
if (fil != "") {
should be:
if (fil != null) {
Edit:
String fil = jTable1.getValueAt(row, 6).toString();
You can't invoke toString() on a null object so you need something like:
Object filObject = jTable1.getValueAt(row, 6);
String fil = (filObject == null) ? "" : filObject.toString();
Then you would use your original test:
If (fil != "")

Java program that outputs an XML file - multiple issues

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;

android app db.execSQL - create two databases sqlite

I am trying to set two databases.
After lunch the emulator, and trying to enter data, I have tried to find the exact reason of this error but without success.
I get an error:
05-17 16:23:06.410: E/AndroidRuntime(311): android.database.sqlite.SQLiteException: near "NULLbaby_age_month": syntax error: CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL, baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT NULLbaby_age_month TEXT NOT NULLbaby_age_day TEXT NOT NULL);
The Database Code is:
package com.tamar.efrat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DatBas {
public static final String KEY_ROWID = "_id";
public static final String KEY_SHOURS = "start_hour";
public static final String KEY_SMINUTE = "start_minute";
public static final String KEY_SDATE = "start_date";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_SIDE = "side";
public static final String KEY_KIND = "kind";
public static final String KEY_ROW_BABY_ID = "_id";
public static final String KEY_BABY_IMAGE_PATH = "uri_baby";
public static final String KEY_BABY_NAME = "baby_name";
public static final String KEY_BABY_GENDER = "baby_gender";
public static final String KEY_BABY_BORN_DATE_YEAR = "baby_age_year";
public static final String KEY_BABY_BORN_DATE_MONTH = "baby_age_month";
public static final String KEY_BABY_BORN_DATE_DAY = "baby_age_day";
private static final String DATABASE_NAME = "TamatDB";
private static final String DATABASE_TABLE = "stop_watch_records";
private static final String DATABASE_TABLE_SETTINGS = "settings";
private static final int DATABASE_VERSION = 20;
private TamarDatabase thdb;
private static Context tcontext;
private SQLiteDatabase tdb;
private static class TamarDatabase extends SQLiteOpenHelper {
public TamarDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String ctData = "CREATE TABLE " + DATABASE_TABLE + " ( "
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SHOURS + " TEXT NOT NULL, " + KEY_SMINUTE
+ " TEXT NOT NULL, " + KEY_SDATE + " TEXT NOT NULL, "
+ KEY_AMOUNT + " TEXT NOT NULL, " + KEY_SIDE
+ " TEXT NOT NULL, " + KEY_KIND + " TEXT NOT NULL );";
db.execSQL(ctData);
String ctSettings = "CREATE TABLE " + DATABASE_TABLE_SETTINGS
+ " ( " + KEY_ROW_BABY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_BABY_IMAGE_PATH + " TEXT NOT NULL, " + KEY_BABY_NAME
+ " TEXT NOT NULL, " + KEY_BABY_GENDER + " TEXT NOT NULL, "
+ KEY_BABY_BORN_DATE_YEAR + " TEXT NOT NULL"
+ KEY_BABY_BORN_DATE_MONTH + " TEXT NOT NULL"
+ KEY_BABY_BORN_DATE_DAY + " TEXT NOT NULL);";
db.execSQL(ctSettings);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SETTINGS);
onCreate(db);
}
}
public DatBas(Context c) {
tcontext = c;
}
public DatBas open() throws SQLiteException {
thdb = new TamarDatabase(tcontext);
tdb = thdb.getWritableDatabase();
return this;
}
public void close() {
thdb.close();
}
public long createEntry(String sh, String sm, String sd, String at,
String tside, String tkind) {
ContentValues cv = new ContentValues();
cv.put(KEY_SHOURS, sh);
cv.put(KEY_SMINUTE, sm);
cv.put(KEY_SDATE, sd);
cv.put(KEY_AMOUNT, at);
cv.put(KEY_SIDE, tside);
return tdb.insert(DATABASE_TABLE, null, cv);
}
public long createEntrySettings(String bbdy, String bbdm, String bbdd,
String pt, String bg, String bfName) {
ContentValues cv2 = new ContentValues();
cv2.put(KEY_BABY_IMAGE_PATH, pt);
cv2.put(KEY_BABY_NAME, bfName);
cv2.put(KEY_BABY_GENDER, bg);
cv2.put(KEY_BABY_BORN_DATE_YEAR, bbdy);
cv2.put(KEY_BABY_BORN_DATE_MONTH, bbdm);
cv2.put(KEY_BABY_BORN_DATE_DAY, bbdd);
return tdb.insert(DATABASE_TABLE_SETTINGS, null, cv2);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_SHOURS, KEY_SMINUTE,
KEY_SDATE, KEY_AMOUNT, KEY_SIDE, KEY_KIND };
Cursor c = tdb.query(DATABASE_TABLE, columns, null, null, null, null,
null);
String results = "";
int iRaw = c.getColumnIndex(KEY_ROWID);
int iShours = c.getColumnIndex(KEY_SHOURS);
int iSminute = c.getColumnIndex(KEY_SMINUTE);
int iDate = c.getColumnIndex(KEY_SDATE);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iSide = c.getColumnIndex(KEY_SIDE);
int iKind = c.getColumnIndex(KEY_KIND);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + "the id is " + c.getString(iRaw)
+ " the sart hour is " + " " + c.getString(iShours)
+ " the start minute is " + " " + c.getString(iSminute)
+ " the start date is " + " " + c.getString(iDate)
+ " the amount is " + " " + c.getString(iAmount)
+ " the side is " + " " + c.getString(iSide)
+ " the kind is " + " " + c.getString(iKind) + "\n";
}
return results;
}
public String getDataSettings() {
String[] columns = new String[] { KEY_ROW_BABY_ID, KEY_BABY_IMAGE_PATH,
KEY_BABY_NAME, KEY_BABY_GENDER, KEY_BABY_BORN_DATE_YEAR,
KEY_BABY_BORN_DATE_MONTH, KEY_BABY_BORN_DATE_DAY };
Cursor c = tdb.query(DATABASE_TABLE_SETTINGS, columns, null, null,
null, null, null);
String results = "";
int iRawBabyId = c.getColumnIndex(KEY_ROW_BABY_ID);
int iBIPath = c.getColumnIndex(KEY_BABY_IMAGE_PATH);
int iBName = c.getColumnIndex(KEY_BABY_NAME);
int iGender = c.getColumnIndex(KEY_BABY_GENDER);
int iBBDateYear = c.getColumnIndex(KEY_BABY_BORN_DATE_YEAR);
int iBBDateMonth = c.getColumnIndex(KEY_BABY_BORN_DATE_MONTH);
int iBBDateDay = c.getColumnIndex(KEY_BABY_BORN_DATE_DAY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results = results + " the kind is " + " " + c.getString(iRawBabyId)
+ " the kind is " + " " + c.getString(iBIPath)
+ " the kind is " + " " + c.getString(iBName)
+ " the kind is " + " " + c.getString(iGender)
+ " the kind is " + " " + c.getString(iBBDateYear)
+ " the kind is " + " " + c.getString(iBBDateMonth)
+ " the kind is " + " " + c.getString(iBBDateDay) + "\n";
}
return results;
}
public DatBas delete() {
tdb.delete(DATABASE_TABLE, null, null);
tdb.delete(DATABASE_TABLE_SETTINGS, null, null);
return null;
}
}
forget to add , in query ...
TEXT NOT NULL,baby_age_month
AND
TEXT NOT NULL,baby_age_day
CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL, baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT NULL,baby_age_month TEXT NOT NULL,baby_age_day TEXT NOT NULL);
having small error : forgetted ( , )separater
CREATE TABLE settings ( _id INTEGER PRIMARY KEY AUTOINCREMENT, uri_baby TEXT NOT NULL,
baby_name TEXT NOT NULL, baby_gender TEXT NOT NULL, baby_age_year TEXT NOT
NULL, baby_age_month TEXT NOT NULL,baby_age_day TEXT NOT NULL);

Categories

Resources