Exhausted Resultset when calling a method inside the while(rset.next) - java

I'm getting an Exhausted resultset form the following code.
I've tried a few different things now and can't find a solution,
if I don't call the songs method it works, but the songs method works when it's called, can't get my head around it, hoping I'm missing something simple.
public void refreshList() {
rset = po.getProduct();
if (plist.size() > 0) {
for (int i = plist.size() - 1; i >= 0; i--) {
plist.remove(i);
}
}
try {
while (rset.next()) {
songs(rset.getString(1));
CD c = new CD(alist);
Product p = new Product(rset.getString(1),
rset.getString(2),
rset.getString(3),
rset.getDouble(4),
rset.getDouble(5),
rset.getInt(6),
rset.getString(7),
rset.getString(8),
rset.getString(9),
rset.getDouble(10), c);
plist.add(p);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
public void songs(String ID)
{
rset = po.getSongs();
alist = new ArrayList<Song>();
try {
while (rset.next()){
Song s = new Song(rset.getString(1),
rset.getString(2),
rset.getString(3));
slist.add(s);
}
}
catch (Exception ea) {
System.out.println(ea);
}
for(int i = 0; i < slist.size(); i++)
{
if(slist.get(i).getSong_id().equals(ID))
{
alist.add(slist.get(i));
}
}
}

Inside refreshList you have while (rset.next()) loop, on each iteration of it you have songs(rset.getString(1));, which itself has while(rset.next(). This leads to result set exhaustion, because when you return from songs() you try to take some more data from the current position of result set, while in songs() you got out of while (rset.next()) loop, i.e. retrieved all its rows. Consider refactoring your code to avoid nested loops based on result set.

Related

Java iterator has suddenly stopped working after a certain point in loop

I have suddenly been having a problem in regards to using an iterator while looping where it only goes through about ⅔ (two thirds) of the array before it seemingly just fails to work properly the last 20,000 elements or so after having worked with the same code previously. The relevant code block is as follows:
private void loadInvTable(){
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
int rowCount = dtm.getRowCount();
try {
invArray = AllJsonData.allQuantityParserTest();
} catch (Exception e) {
e.printStackTrace();
}
Iterator<InventoryData.InventoryObject> invIt = invArray.iterator();
for(int i = 0; i < rowCount; i++){
String upc = dtm.getValueAt(i, dtm.findColumn("UPC")).toString();
while (invIt.hasNext()){
InventoryData.InventoryObject invObj = invIt.next();
String test = invObj.getUpc().toString();
if(invObj.getUpc().equals(upc)){
System.out.println(invObj.getUpc());
dtm.setValueAt(invObj.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(invObj.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(invObj.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(invObj.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(invObj.getDam(), i, dtm.findColumn("DAM"));
invIt.remove();
break;
}
}
}
invArray.clear();
}
The data it is comparing is an array parsed from a file and a JTable each with about 100,000 rows. The problem being is that when I do it in other ways it takes much longer but works properly:
private void loadInvTable() {
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
try {
invArray = AllJsonData.allQuantityParserTest();
} catch (Exception e) {
e.printStackTrace();
}
int rowCount = dtm.getRowCount();
for(InventoryData.InventoryObject inv : invArray){
for(int i = 0; i < rowCount; i++){
if(dtm.getValueAt(i, dtm.findColumn("UPC")).toString().equals(inv.getUpc())){
dtm.setValueAt(inv.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(inv.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(inv.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(inv.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(inv.getDam(), i, dtm.findColumn("DAM"));
break;
}
}
}
}
private void loadInvTable() {
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
InventoryData.InventoryObject invObj;
try {
invArray = AllJsonData.allQuantityParserTest();
//System.out.println(ints);
} catch (Exception e) {
e.printStackTrace();
}
Iterator<InventoryData.InventoryObject> invIt = invArray.iterator();
int count = 0;
int rowCount = dtm.getRowCount();
while(invIt.hasNext()){
invObj = invIt.next();
for(int i = 0; i < rowCount; i++){
if(dtm.getValueAt(i, dtm.findColumn("UPC")).toString().equals(invObj.getUpc())){
dtm.setValueAt(invObj.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(invObj.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(invObj.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(invObj.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(invObj.getDam(), i, dtm.findColumn("DAM"));
invIt.remove();
break;
}
}
count++;
}
}
I tried to both rewrite and debug the problem section of the program, but I can't seem to find a way to code it so that it works nearly as quickly the first block and when debugging the code it seems to either hang on the code block and I need to kill the program or it runs and just skips/repeats one of the the rest of the elements in the array.
I have no idea what exactly I'm doing wrong and am even having trouble pinpointing what could be causing the issue or what had changed to break it and have been trying for days to get it working again. I was hoping for some help if anyone can point where the mistake is. If this question has already been asked elsewhere I apologize. I couldn't find a similar question anywhere. Thanks in advance for any help anyone can provide.

I am getting en error for the misplaced return statement while retriving the values for a particular ssnum from the mysql database

public Customer getCustomer(String ssNum) throws CustomerHomeException, ClassNotFoundException {
String query = "Select ssn, customer_name from customer ";
ResultSet rs = smt.executeQuery(query);
Customer customer = null;
while (rs.next()) {
if (ssNum.equals(rs.getString("ssn"))) {
customer = new Customer(rs.getString("ssn"), rs.getString("customer_name"));
}
return customer;
}
} catch (SQLException e) {
throw new CustomerHomeException("Failed to create CustomerHome", e);
}
}
I'm getting an error for the return statement placed while retriving the value from the MySQL database. Value already exists.
Method getCustomer expecting to return customer at the end of function definition. and you are returning in the middle of while loop. So Compiler complaining to add or place return statement as your method suppose to, because its not always happening that while or if will get executed every time.
private static int hello() {
for (int i = 0; i < 2; i++) {
return 0;
}
return -1;
}
I hope this helps.

J2ME PIM get contacts number alone

Is there a way I can read a contacts number using the PIM API. I'm using the code below and it's just returning the name. I want the code to return the number only from a contact.
pim = PIM.getInstance();
ContactsList.setModel(new DefaultListModel());
try {
String[] pimListNames = pim.listPIMLists(PIM.CONTACT_LIST);
for (int i = 0; i < pimListNames.length; ++i) {
ContactList cl = (ContactList) pim.openPIMList(
PIM.CONTACT_LIST, PIM.READ_ONLY, pimListNames[i]);
Enumeration items = cl.items();
while (items.hasMoreElements()) {
Contact c = (Contact) items.nextElement();
ContactsList.addItem(c.getString(Contact.FORMATTED_NAME, 0));
}
}
} catch (PIMException ex) {
WittyClassObject.showAlert("error", ex.toString());
}
Have you tried to use
c.getString(Contact.TEL, 0) // instead of c.getString(Contact.FORMATTED_NAME, 0) ?

Unable to update value of gobal variable in threads

I am not able to update the value of a global variable in a function which is called continuously by a thread
The function code is:
public void readMessages()
{
if (srv.getServiceStatus() == Service.ServiceStatus.STARTED) {
try {
InboundMessage msg = null;
java.util.LinkedList<InboundMessage> list = new java.util.LinkedList<InboundMessage>();
srv.readMessages(list, InboundMessage.MessageClasses.UNREAD);
int checkArray = list.size();
for (int i = 0; i < list.size(); i++) {
msg = list.get(i);
System.out.println("New incoming message from: " + msg.getOriginator() +" : \t" + msg.getText() + "\n");
saveSMS(msg.getOriginator(),msg.getText());
if (checkArray == 0) {
messageArray = new String [4];
for (int j = 0 ; j<4 ; j++) {
messageArray[j] = "";
}
}
if (noOfSms < 4) {
messageArray[noOfSms] = msg.getText();
noOfSms = noOfSms + 1;
}
if (noOfSms == 3) {
Receiver r = new Receiver ();
r.Processing_ReceivedSMS(msg.getText(),msg,messageArray);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
Here noOfSms is the global variable but its value does not change.
The function from which readMessage is called is this:
public void run(){
while (true){
readMessages();
try {
t.sleep(5000);
user_status=2;
} catch (InterruptedException e) {
System.out.println("Thread Pause Exception");
}
}
}
What's the reason behind it and what to do about it?
Since you invoke this method from thread/s there are two reasons why your variable does not get updated.
the code inside readMessages() might throw any Exception before your variable gets updated
there is a possibility that your variable never updates because it is located inside if blocks. Check the initial value of it so it can pass the if-condition

How to read a List in batches

I have a function which reads a List of Notifications Object. Now I have to read the Notifications object in batches of 100(suppose) and update it.
public boolean addBSInfoToTemp(List<ParentNotification> pNotify)
throws DaoException, BatchUpdateException {
int cnt = 0;
final String query = "insert into Temp values ?,?,?,'Y','N',?,?,?,?";
while (!pNotify.isEmpty()) {
try {
pst = getConnection().prepareStatement(query);
for (ParentNotification pn : pNotify) {
cnt++;
pst.setInt(1, pn.getUserId());
pst.setString(2, pn.getEmail());
pst.setString(3, pn.getNotificationType());
Date createdDate = (Date) pn.getCreatedDate();
pst.setDate(4, createdDate);
pst.setString(5, pn.getCreatedBy());
Date icsesCreatedDate = (Date) pn.getIcsesCreatedDate();
pst.setDate(6, icsesCreatedDate);
pst.setString(7, pn.getMiscellaneous());
pst.addBatch();
if(cnt==batchCount){
break;
}
}
int[] batch = pst.executeBatch();
if (batch.length != 0) {
flag = true;
}
} catch (BatchUpdateException b) {
flag = false;
} catch (SQLException sqlx) {
flag = false;
} finally {
close(pst, null);
}
}
return flag;
}
What I am trying to do is read the List with batchCount = 100 then update and go back to 101 record and then update another 100 records untill the List is empty.
You have this:
while (!pNotify.isEmpty()) {
but I don't see that you ever remove objects from the list, so you have infinite loop. I would just make the outside loop to loop through all of the elements like this:
for (int i=0; i<=pNotify.size(); i++){
// and inside check if it is devisible by batch length
if(i % batchCount == 0){
break;
}
}

Categories