I have a program which requires me to input the ID of a product and then will search a database in order to display details about that specific product.
The code works fine for every item in the database except productID 2 and productID 4 because they have no data stored in one of the columns (PRODUCT_TYPE).
I've got an if statement in my code which says:
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION ") == null)
{
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nProduct type: null.");
}
But I cannot figure out why it's unable to find the product if Product type is null but can still find it if description is null.
try{
String searchCode = "SELECT PRODUCTS.PRODUCT, PRODUCTS.COST, PRODUCTS.DESCRIPTION, PRODUCT_STOCK.STOCKITEM , PRODUCT_STOCK.STOCKLEVEL FROM PRODUCT_TYPE INNER JOIN (PRODUCTS FULL OUTER JOIN PRODUCT_STOCK ON PRODUCTS.PRODUCTID = PRODUCT_STOCK.STOCKITEM) ON PRODUCT_TYPE.PRODTYPEID = PRODUCTS.PRODUCT_TYPE WHERE PRODUCTID = " + inputValue + ";";
// sql statement searches the database for the required data
Statement statement = dbConnection.createStatement();
ResultSet result = statement.executeQuery(searchCode);
boolean found = false;
found = result.next();
if (!found) { //if no data is found then display the error message and restart the product search method
System.out.println("That product couldn't be found, please try again.");
searchProduct();
}
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION ") == null)
{
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nProduct type: null.");
}
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION") != null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: " + result.getString("DESCRIPTION") + ". \nProduct type: null.");
}
else if (result.getString("PRODUCT_TYPE") != null && result.getString("DESCRIPTION") == null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: null. \nProduct type: " + result.getString("PRODTYPE_DESC") + ".");
}
else if (result.getString("PRODUCT_TYPE") != null && result.getString("DESCRIPTION") != null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: " + result.getString("DESCRIPTION") + ". \nProduct type: " + result.getString("PRODTYPE_DESC") + ".");
}
}
catch (Exception e){ // if the product can't be found then display the error message and restart the product search method
System.out.println("Could not find product.");
System.out.println(e.toString());
searchProduct();
}
//goes back to menu once the method has finished
askUser();
}
Any help would be massively appreciated. Thanks.
Do you have a typo?
result.getString("DESCRIPTION ") == null
Should be
result.getString("DESCRIPTION") == null
Note the extra space in "Description " in your current version.
Related
I'm building an Android app that contain SQLite DB and I was having a problem with translating SQLite saved data then I find a solution which is a method to get resource id of strings, and it worked just fine, the app was working fine then suddenly this error showed I don't know why, please help
The method, I used to get resource for string:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
The code in the adapter
textViewname.setText(context.getString(R.string.product_Name)+" " + repo.getName());
textViewquantity.setText(context.getString(R.string.last_added_qty)+" " + repo.getQuantity() + " " + context.getResources().getString(mdatabase.getResId(repo.getItemsType(),R.string.class)));
textViewdate.setText(context.getString(R.string.entry_date)+" " + repo.getDate()+ " /"+context.getResources().getString(mdatabase.getResId(repo.getInOrOut(),R.string.class)));
textViewTotal.setText(context.getString(R.string.total_qty)+" " + repo.getTotal() + " " + context.getResources().getString(mdatabase.getResId(repo.getItemsType(),R.string.class)));
textviewlastUpdated.setText(context.getString(R.string.last_updated_date)+" " + repo.getUpdateDate() +" /"+context.getResources().getString(mdatabase.getResId(repo.getInOrOut(),R.string.class)));
textViewid.setText(context.getString(R.string.id)+" " + repo.getId());
textViewOutputqty.setText(context.getString(R.string.last_out_qty)+" " + repo.getOutputqty() + " " + context.getResources().getString(mdatabase.getResId(repo.getItemsType(),R.string.class)));
textViewpriceofsingleitem.setText(context.getString(R.string.retail_price)+" " + repo.getPrice() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewpriceofMultipleitem.setText(context.getString(R.string.wholesale_price)+" " + repo.getPriceofmultipleInput() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewProfitSIngle.setText(context.getString(R.string.retail_profit)+" " + repo.getProfitSingle() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewProfitMultiple.setText(context.getString(R.string.wholesale_profit)+" " + repo.getProfitMultiple() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewPurchasingPrice.setText(context.getString(R.string.purchasing_price)+" " + repo.getPurchasingPricePeranItem() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewTotalPurchasingPrice.setText(context.getString(R.string.total_purchase_price)+" " + repo.getTotalPurchasingPrice() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewTotalProfitSingle.setText(context.getString(R.string.total_retail_profit)+" " + repo.getTotalProfitperSingle() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewTotalProfitMultiple.setText(context.getString(R.string.total_wholesale_profit)+" "+ repo.getTotalProfitPerMultiple() + " " + context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewitemsIBox.setText(context.getString(R.string.num_unitsInBox)+" "+ repo.getItemsInBox());
textViewSinglePriceOfiteminBox.setText(context.getString(R.string.retail_price_perUnit)+ " " + repo.getSinglePriceofItemInBox()+" " +context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewMultipriceOfItemInBox.setText(context.getString(R.string.wholesale_price_perUnit)+" "+repo.getMultiplePriceofitemInBox()+" "+context.getResources().getString(mdatabase.getResId(repo.getCurrency(),R.string.class)));
textViewtotalItemsInBoexs.setText(context.getString(R.string.total_units)+" "+ repo.getTotalitemsInboxes() +" "+ context.getResources().getString(R.string.Pieces));
This error happens because you are trying to get resource that does not exist. It is because you store memory address which allocate to your string resource and possible it will change next time. I do not know what is your scenario but why you store it already in your strings it will never lost. I can help you to build another logic only when you tell what are you trying to achieve.
I want to achieve AutoSuggest ComboBox 2 problems I am facing
1st getting an array of id and name both want the name only.
Array i am receiving
2nd losing focus on typing the text.
Please help
database Query
public SentenceList getAutoProductList() {
return new StaticSentence(s, "SELECT "
+ "P.ID, "
+ "P.REFERENCE, "
+ "P.CODE, "
+ "P.CODETYPE, "
+ "P.NAME, "
+ "P.PRICEBUY, "
+ "P.PRICESELL, "
+ "P.CATEGORY, "
+ "P.TAXCAT, "
+ "P.ATTRIBUTESET_ID, "
+ "P.STOCKCOST, "
+ "P.STOCKVOLUME, "
+ "P.IMAGE, "
+ "P.ISCOM, "
+ "P.ISSCALE, "
+ "P.ISKITCHEN, "
+ "P.PRINTKB, "
+ "P.SENDSTATUS, "
+ "P.ISSERVICE, "
+ "P.ATTRIBUTES, "
+ "P.DISPLAY, "
+ "P.ISVPRICE, "
+ "P.ISVERPATRIB, "
+ "P.TEXTTIP, "
+ "P.WARRANTY, "
+ "P.STOCKUNITS "
+ "FROM PRODUCTS P "
+ "ORDER BY NAME", null, ProductInfoExt.getSerializerRead());
}
Auto Complete JcomboBox Code
SentenceList sentProductNames = dlSales.getAutoProductList();
m_JComboProductName.setEditable(true);
ComboBoxValModel m_jProductNameModel = new ComboBoxValModel();
editor = (JTextComponent) m_JComboProductName.getEditor().getEditorComponent();
List productList = null;
try {
productList = sentProductNames.list();
} catch (Exception e) {
}
productList.add(0, null);
m_jProductNameModel = new ComboBoxValModel(productList);
m_JComboProductName.setModel(m_jProductNameModel);
AutoCompleteDecorator.decorate(m_JComboProductName);
System.out.println("product List "+ productList);
if(m_JComboProductName.getItemCount()>0){
m_JComboProductName.setSelectedIndex(0);
}
Hi this is some code I've constructed for a project which calls several other methods to print a statement about the person. My problem is its printing in double and appears to be running through both if/else statements.
How can I prevent this? if needed I can add the text from my terminal. Code below;
void printPersonDescription(String name, boolean sex, int age) {
if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " +
nextMaturityLevel(age) + ".");
}
else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " +
nextMaturityLevel(age) + ".");
}
if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " +
nextMaturityLevel(age) + ".");
}
else {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " +
nextMaturityLevel(age) + ".");
}
}
Note how similar your four cases are. You are just changing some words in the line you print. Those four if/else blocks can be simplified to this:
void printPersonDescription(String name, boolean sex, int age) {
int years = yearsUntilNextMaturityLevel(age);
String gender = sex ? "she" : "he";
String plural = years > 1 ? "s" : "";
println(name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" " + gender + " has " + years + " year" + plural + " left until " + gender + " is " +
nextMaturityLevel(age) + ".");
}
Also, you can make the println a bit more readable by using String.format (assuming that the maturity levels are strings)
String.format("%s is %s. At %d %s has %d year%s left until %s is %s.",
name, getMaturityLevel(age), age, gender, years, plural, gender,
nextMaturityLevel(age))
Third if condition should be else if in your code to avoid double printing.
Instead of:
if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
Use:
else if (sex && yearsUntilNextMaturityLevel(age) <= 1) {
btw you don't need to use if (boolVar == true) you can just use if (boolVar)
void printPersonDescription(String name, boolean sex, int age) {
if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " +
nextMaturityLevel(age) + ".");
}
else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " +
nextMaturityLevel(age) + ".");
}
else if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " +
nextMaturityLevel(age) + ".");
}
else {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " +
nextMaturityLevel(age) + ".");
}
}
You need add else before the third if. Otherwise, the final else statement will match the third if, thus, the else statement means
if(sex != true || yearsUntilNextMaturityLevel(age) > 1)
I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...
okay i have source like this
public List<SearchRecord> getResult() {
List<SearchRecord> searchResult = new ArrayList<SearchRecord>();
String query = "SELECT " + A + ", " + B+ ", " + C
+ " FROM " + TABLE_A+ " UNION ALL SELECT " + A+ ", "
+ B+ ", " + C+ " FROM " + TABLE_B + " UNION ALL SELECT " + A+ ", " + B+ ", "
+ C+ " FROM " + TABLE_C + " UNION ALL SELECT "
+ A+ ", " + B+ ", " + C+ " FROM "
+ TABLE_D;
Cursor cursor = mDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
do {
SearchRecord sr = new SearchRecord();
sr.setRecordA(cursor.getString(0));
sr.setRecordB(cursor.getString(1));
sr.setRecordC(cursor.getString(2));
searchResult.add(sr);
} while (cursor.moveToNext());
return searchResult;
}
return null;
}
with this code i can get some record from multiple table who have same column name, and store the result in a List object. but how to i find out which table is this record belongs ? is it from TABLE_A, TABLE_B, TABLE_C, or the other
As per SQL, no, you are joining 3 sets of rows and operating them the same way, each record cannot be distinguished by its origin.
Of course, you could do something like
String query = "SELECT 'TABLE_A', " + A + ", " + B+ ", " + C
+ " FROM " + TABLE_A+ " UNION ALL SELECT 'TABLE_B' " + A+ ", "
+ B+ ", " + C+ " FROM " + TABLE_B
+ " UNION ALL SELECT 'TABLE_C', " + A+ ", " + B+ ", "
+ C+ " FROM " + TABLE_C + " UNION ALL SELECT 'TABLE_D', "
+ A+ ", " + B+ ", " + C+ " FROM "
+ TABLE_D;
:-)