Iteration problem

I have a list. It may or may not contain elements. I want to iterate through the list and where the element is not equal to null, cast it to a string and print it out to the screen.
There are two problems i get with my code, 1 is it doesn't read the first element and secondly i get a java.util.NoSuchElementException.
Anyone got any ideas?
Iterator iter = factList.iterator();
if(iter.hasNext())
     while(list.contains((String)iter.next()))
          content = (String)iter.next();
          System.out.println(content);
}

LinkedList is a little confusing because it also implements Queue.
The following are all pretty similar:
Object a = l.get(0);
Object a = l.getFirst();
Object a = l.peek();
Object a = l.element();The all return the first element, none alter l. (One difference is that some
of them have a runtime exception if l is empty!)
You ask "would that assign then remove". I'm not sure what you are
trying to say, but I think you should write a short example program a
try out a few things to find out how these methods work yourself.
It will only take a few minutes and you'll learn more than posting
questions on these forums. Save the forums for questions when you
are stuck.

Similar Messages

  • Query update on each iteration problem (MS SQL Sever / ODBC / Native Driver

    Hello,
    I�ve been working to learn some Java and now JDBC over the past 10 or so months.
    I think I have a general understanding of how to perform queries and work with data using JDBC. However, I�ve run into a problem. I�m trying to do a query of a set of data in a database based on the value of a status column. I want to loop over the messages and perform various functions with the data then update their status in the database. It�s preferable to do these 250 to 1000 rows at a time, but no more and no less.
    I�m connecting to MS SQL Server 2000, currently with ODBC. I�ve also tried it with the Java SQL Server 2000 drivers provided by Microsoft with the same results.
    I�ve found that I can do a one table query and loop though it with a while (rs.next()) {�} and run an Update statement with executeUpdate on each iteration without any problems, no matter the number of rows returned in query.
    I have not been able to use the updateString and updateRow inside the while loop. I keep getting errors like this at the line with the updateRow():
    Exception in thread "main" java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Row update failed.
    This occurs no mater how many rows I select, 1 or more.
    The real problem I�ve been having is that the query I need to loop though joins across several tables and returns some rows from some of those tables. This only seems to work when I query for 38 or less selected rows and I use an Update statement with executeUpdate on each iteration. The updateString and updateRow methods never work. Any number of rows selected greater than 38 causes a deadlock where the Update is waiting for the select to compete on the server and the Update can�t proceed until the Select is complete.
    As I stated above I�ve tried both ODBC and the native SQL Server driver with the same results. I have not tried any other databases, but that�s moot as my data is already in MS SQL.
    Questions:
    How can I avoid or get around this 38 row limit without selecting each row, one at a time?
    What am I doing wrong with the updateString and updateRow?
    Is there a better approach that anyone can suggest?
    Here�s some sample code with the problem:
    import java.sql.*;
    public class db1{
         public static void main(String[] args) throws Exception{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String url = "jdbc:odbc:eBrochure_live";
              Connection con = DriverManager.getConnection(url, "sa", "d3v3l0p");
              Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
              Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://dcm613u2\\dcm613u2_dev:1433", "sa", "d3v3l0p");
              Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
              Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
              stmt.executeUpdate("USE [myDatabase]");
              stmt2.executeUpdate("USE [myDatabase]");
              String qGetMessages = "SELECT TOP 250 t1.messageUUID, t1.subjectHeader, t2.emailAddress as toAddress " +
              "FROM APP_Messages as t1 JOIN APP_addressBook_contacts as t2 " +
              "     On t1.toContactID = t2.contactID " +
              "WHERE t1.statusID = 'queued'";
              ResultSet rs = stmt.executeQuery(qGetMessages);
              while (rs.next()) {
                   String messageUUID = rs.getString("messageUUID");
                   String subjectHeader = rs.getString("subjectHeader");
                   System.out.println(messageUUID + " " + subjectHeader);
                   String updateString = "UPDATE APP_Messages " +
                        "SET statusID = 'sent' " +
                        "WHERE messageUUID = '" + messageUUID + "' ";
                   stmt2.executeUpdate(updateString);
              con.close();
    Thanks for the help,
    Doug Hughes

    // sorry, ps.close() should be outside of if condition
    String sql = "UPDATE APP_Messages SET statusID = 'sent' WHERE messageUUID = ?";
    Statement statement = con.createStatement();
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = statement.executeQuery("your select SQL");
    if ( rs.next() )
    ps.clearParameters();
    ps.setString(1, rs.getString("your column name"));
    ps.executeUpdate();
    ps.close();
    rs.close();
    statement.close();

  • Main window iteration problem in smart forms

    Hai,
    I am struggling from a problem from past 1 weak, can anybody help me.
    Problem:
    user- inputs: 2 different items say item1 and item2.
    The output should be the combinations of four pages(pg1,pg2,pg3,pg4)  based on conditions.
    pg1 should be displayed when:
         1. item1 and item2 are less than 5.
         2. either pg1 or pg2 are less than 5.
    note: pg1 can only display 5 items of each type.
    pg2 should be displayed when:
        1.item1/item2 is greater than 5 and less than 15.
        2. either item1/item2 >5 and <=15 .
    note: pg1 can only display 15 items of each type.
    pg3 should be displayed when:
        item1 is greater than 15.
    pg4 should be displayed when
       item2 is greater than 15.
    My problem is when there are items greater than 15 say 90 items then main window page is not iterated i.e only first 40 is displayed remaining are not displayed.
    Please help me as soon as possible.
    Helpful answers will be rewarded.
    Thanks and Regards,
    Swetha Singh.

    Hi,
    Instead of calculating the line items, you can use the command in the footer of the main table to go to next page. It will dynamicaly push to the next page, once first page data display was over.
    Is this the answer you are looking for. Thanks.

  • Struts/ADF Iterator problem - how to prevent iterator from executing?

    HI
    I've a problem with a iterator which I would like NOT to execute before I order it! This is a basic Struts/ADF app developed in JDeveloper 9052 and I really don't understand why this iterator is executed!
    My binding definition file for the page contains 2 iterators, let say iterator A and B. Each iterator is bound to a different viewobject. Viewobject bound to iterator A i straightforward, but viewobject bound to iterator B has 3 bind variables - and then I don't want iterator B to execute before i have specified values for those, but I can't hold it back!
    The bindingcontainer is forced into FindMode to prevent any iterator to execute in the first place - then I thought that I would be completely in control. This works fine, until I need to execute iterator A without executing B or any other iterator. I've overridden the prepareModel() method, to accomplish this:
    protected void prepareModel(DataActionContext ctx) throws Exception {
    DCBindingContainer con = ctx.getBindingContainer();
    JUCtrlActionBinding action = (JUCtrlActionBinding)con.findCtrlBinding("ExecuteA");
    action.invoke();
    But, executing iterator A this way, also automatically executes iterator B somehow, which causes a classic JBO-27122 (not all variable bound...). If I remove the code for manually executing iterator A, I get no error, because no iterator is fired at all then. But how do I only execute one iterator in the binding container???
    To demonstrate, my JSP page only has this content:
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <html:errors/>
    Regards
    Jacob

    I don't think you can stop that.
    What I usually do to prevent result show up is to add additional condition with bind variable to programmatically make it selecting no row. vo is something like
    select aField
    from someTable
    where .....
    and :toSearch = 'Y'
    the bind variable :toSearch will be default to 'N'

  • Iteration problem in method...

    Hi everyone,
    I'm having a little problem here... I have this loop in a method that should iterate Xml Paths and in the loop it uses that Xml Path to do several things like get information from it. Now, the XML Path is being used correctly (meaning, it uses different values) to get information from it, but when it is passed in a method that is being started by an action (a press on a button), it seems to pick the last xmlPath variable that the loop gave. Hope this makes sence!
    Here's the code:
    populateObjectList();
            int objectNr = 0;
            int row = 0;
            for(Object o : objectList)
                objectNr++;
                xmlPath = o.toString();
                System.out.println(xmlPath);
                ConfigList iconObject = new ConfigList(xmlPath);
                int iconX = objectPanel.x + 20;
                int iconY = objectPanel.y + 20;
                if (objectNr == 2)
                    iconX = iconX + 48;
                if (objectNr == 3)
                    row++;
                    objectNr = 0;
                    iconY = iconY + 36 * row;
                // Image
                iconFrame = iconObject.icon.get(objectDirection).toString();
                iconImg = new GUIImage(iconFrame, iconX + 2, iconY + 2, objectPanel);               
                objectPanel.add(iconImg);
                // Icon
                iconBtn = new GUIButton(iconX, iconY,48,36,objectPanel,new ButtonListener(){
                public void buttonPressed()
                    //System.out.println("XML Path: " + xmlPath);
                    setPlaceObject(xmlPath);
                iconBtn.setImage("border");
                iconBtn.setToggle(true);
                objectPanel.add(iconBtn);
            }And the method that puts the xml paths in:
    public void populateObjectList()
            objectList.add("src\\xmls\\object1.xml");
            objectList.add("src\\xmls\\object2.xml");
        }So the xmlPath in the "buttonPressed" function is always "src\\xmls\\object2.xml".
    Hope you folks understand my problem! If not, tell me what you don't understand :)
    Thanks ahead!
    Jens

    Sorry for the double posts, but I have another problem... Again with the iteration! The iconFrame string should change if the objectDirection string changes. However, it doesn't... The objectDirection changes when I click a button, so I figured I would just put the loop in the method and call that method when that button is clicked, but that doesn't overwrite the icons, it just adds more (as that method with the loop in it is also called by default when the button is not clicked...
    Here's the changed code:
    Default call in the constructor method:
    populateObjectList();Method that changes the objectDirection variable:
    public void rotateAnimation(int nr)
            if (nr == -1)
                rotateNr--;
            if ((nr == -1) && (rotateNr == -4))
               rotateNr = 0;
            switch(rotateNr)
                case 0:
                    objectDirection = "South";  
                    break;
                case -1:
                    objectDirection = "East";
                    break;
                case -2:
                    objectDirection = "North";
                    break;
                case -3:
                    objectDirection = "West";
                    break;
            populateObjectList();
        }The old method with the loop added in:
    public void populateObjectList()
            objectList.add("src\\xmls\\object1.xml");
            objectList.add("src\\xmls\\object2.xml");
            int objectNr = 0;
            int row = 0;
            for(Object o : objectList)
                objectNr++;
                final String xmlPath = o.toString();
                System.out.println(xmlPath);
                ConfigList iconObject = new ConfigList(xmlPath);
                int iconX = objectPanel.x + 20;
                int iconY = objectPanel.y + 20;
                if (objectNr == 2)
                    iconX = iconX + 48;
                if (objectNr == 3)
                    row++;
                    objectNr = 0;
                    iconY = iconY + 36 * row;
                // Image
                iconFrame = iconObject.icon.get(objectDirection).toString();
                iconImg = new GUIImage(iconFrame, iconX + 2, iconY + 2, objectPanel);               
                objectPanel.add(iconImg);
                // Icon Button
                iconBtn = new GUIButton(iconX, iconY,48,36,objectPanel,new ButtonListener(){
                public void buttonPressed()
                    //System.out.println("XML Path: " + xmlPath);
                    setPlaceObject(xmlPath);
                iconBtn.setImage("border");
                iconBtn.setToggle(true);
                objectPanel.add(iconBtn);
        }Does this make sence? Does anyone have a solution for this? Again, if you don't understand, please tell me!
    Thanks ahead!
    Jens

  • Iteration problem. Please GUIDE.

    i am facing a tricky problem
    I have a predefined RowsetIterator tag which iterates over a datasource
    So if a datasource has 20 rows,the iterator will go over each row.
    displayPositions.jsp
    <pd:RowsetIterator   datasource="ViewObject" >
        <mytag:DetailRowsIterate>
    </pd:RowsetIterator>The above code displays all 20 rows.Thats fine.
    There is a slight change in the functionality.
    I need to display the next row after the current row.
    ie,display the next row after current record.
    So i wrote by own tag called 'DetailRowsIterate' as a nested tag.
    This tag looks at the datasource and displays the next record
    after the current record.(So i can view 10 records only.right?)
    The problem is that i can i can see the 10 records on the system.out.println
    but not on my JSP page.
    I can view the 10 records on my System.out.println and then the 20 records
    gets displayed in the JSP Page.I dont want that.I want the 10 records only
    to be displayed by the page.
    I tried using 'DetailRowsIterate' as a nested tag but still,its displays the
    10 records first on the System,out.println() and then the 20 records
    on the JSP Page.
    I tried this
    <jbo:RowsetIterate datasource="<%=dsParam%>" changecurrentrow="false" userange="true">
          <imjbo:DetailRowsIterate >
                 <imjbo:DisplayValue />  
           </imjbo:DetailRowsIterate />
        </jbo:RowsetIterate>No luck.
    iS THERE A FAULT IN MY DetailRowsIterate tag?
    This is the code
    public class CheckDetailRowsIterate extends TagSupport
         public int doStartTag() throws JspException
           /* Just for Seeing data values. */
           StatusLog log = StatusLog.getLogger();
           String ClassName = this.getClass().getName();
           Row currentRow = null;
           Row nextRow = null;
           ViewObject vo = null;
           DataSource dataSource = null;
           /* Get the Current Row data */
           String c_CmpyCode;
           /* Get the Next Row data */
           String n_CmpyCode;
           /* Find the current row and get Data out of it */
           RowsetIterateTag detailIterator = (RowsetIterateTag)TagSupport.findAncestorWithClass(this, RowsetIterateTag.class);
           if (detailIterator != null)
              currentRow = detailIterator.getRow();
              dataSource =  detailIterator.getDataSource();
           else
               // No row iterator
           if(currentRow != null)
             String[] attrNames = currentRow.getAttributeNames();
             Object[] obj = currentRow.getAttributeValues();
             // Get the attribute Values of the Current Row.
             c_CmpyCode = obj[currentRow.getAttributeIndexOf("CmpyCode")].toString();
             // Obtain an ApplicationModule.
             ApplicationModule am  = dataSource.getApplicationModule();
             // Get the DataSourceName.
             String dataSourceName = detailIterator.getDataSourceName();
             // Obtain a View Object by passing the dataSourceName.
             vo = am.findViewObject(dataSourceName);  
             // Go the current record.
             nextRow = vo.next();
             if(vo.hasNext())
               nextRow = vo.next();  // Go to the record after the 'current record',
                                     // this is the next row after the current row.
               attrNames = nextRow.getAttributeNames();
               obj = nextRow.getAttributeValues();
               // Get the attribute Values for the NEXT RECORD.
               n_CmpyCode = obj[nextRow.getAttributeIndexOf("CmpyCode")].toString();
              System.out.println(NEW NEXT ROW Values ARE : " + n_CmpyCode);
               // Extremely Important.
               nextRow = vo.previous();                                                              
             }  // End if(vo.hasNext())
            }  // End if(currentRow !=null)
            //return Tag.SKIP_BODY;
            return EVAL_BODY_INCLUDE;
         } // End of doStartTag()
    }  // End class.

    How do you know it is not working?

  • Content Iterator Problem

    Hi There,
    For Solving the large list threshold error i recently added content iterator concept to my application code. 
    But in my case, it is showing threshold error even after  implementing content iterator concept.
    I followed all the rules as for as Content iterator is concerned. and after research in all the websites i am asking you this question.

    Hi ,
    Thanks for looking into this.
    In Test environment, there are 6500 items in document library. And Hence Set
    List View Threshold Limit to
    5000 in the Web Application. When we query to document library using Content Iterator Concept, we get following error message.
    "The Attempted Operation is prohibited because it exceeds List view Threshold enforced by Administrator."
    Please refer below code written.
    public static DataTable SearchQueryContentIterator(string strQuery, SPList somList)
    SPListItemCollection itemcoll = null;
    DataTable dtResults = new DataTable();
    ContentIterator contentiterator = new ContentIterator();
    try
    SPQuery query = new SPQuery();
    query.RowLimit = 2000;
    query.QueryThrottleMode = SPQueryThrottleOption.Override;
    query.Query = strQuery + ContentIterator.ItemEnumerationOrderByNVPField;
    query.ViewAttributes = "Scope=\"RecursiveAll\"";
    query.ViewFields = string.Concat(
    "<FieldRef Name='ProjectNumber' />",
    "<FieldRef Name='ProjectName' />",
    "<FieldRef Name='SalesOrderNumber' />",
    "<FieldRef Name='SMSIDNumber' />",
    "<FieldRef Name='ContentType' />",
    "<FieldRef Name='PONumber' />",
    "<FieldRef Name='EndUser' />",
    "<FieldRef Name='ProjectManager' />",
    "<FieldRef Name='Purchaser' />",
    "<FieldRef Name='Title' />",
    "<FieldRef Name='ID' />",
    "<FieldRef Name='EncodedAbsUrl' />",
    "<FieldRef Name='FileLeafRef' />",
    "<FieldRef Name='FileRef' />"
    query.Query = strQuery;
    query.ViewFieldsOnly = true;
    contentiterator.ProcessListItems(somList, query,
    delegate(SPListItemCollection listItems)
    itemcoll = listItems;
    if (itemcoll != null)
    if (itemcoll.Count > 0)
    dtResults.Merge(itemcoll.GetDataTable());
    }, null);
    return dtResults;
    catch (Exception ex)
    throw;
    In the Query, we have added Index to Columns used in Where Clause
    Condition.
    FYI, In Production environment, Document Library Contains 60,000 Items. Administrator not ready to increase List View Theshold Limit more than 10000.
    Please assist on this. Waiting for your reply...

  • Custom iterator problem - The method createChildIterator() is undefined for

    Hi there, this is my first post here, still quite new to Java. I'm having trouble with a custom iterator when trying to test it with JUnit. The reason to write a custom iterator is this: I want to get the object in the array, then for each item I want to get it's child items with a new iterator call.
    It's quite complicated because naturally I'm trying to hide the implementation from the "user". The iterator holds a list of classes called StandardSortElement. Each of these classes holds a class called AvailableResouce
    which in turn holds an AbstractResource, and it's AbstractResource that I want the iterator to return. My JUnit testing shows that this part works correctly.
    For the child items, they are also held inside the StandardSortElement as an array list. Here is the error I get
    "The method createChildIterator() is undefined for the type Iterator<AbstractResource>"
    First here is an interface for the custom iterator:
    public interface SortIteratorInterface extends Iterator<AbstractResource>{
         public abstract Iterator<BookingInterface> createChildIterator();
    }Here is the iterator class:
    public class StandardSortIterator implements SortIteratorInterface {
         ArrayList<StandardSortElement> items;
         Integer position = 0;
         * a constructor that passes in a sorted list of StandardSortElement
         public StandardSortIterator(ArrayList<StandardSortElement> items) {
              this.items = items;
         * Return bookings associated with the currently iterated StandardSortElement
         public Iterator<BookingInterface> createChildIterator() {
              return items.get(position).createBookingIterator();
         * Determine if there is another item in the list
         public boolean hasNext() {
              if (position >= items.size()) {
                   return false;
              } else {
                   return true;
         * Return the next resource in the list. We have a list of StandardSortElement but
         * we want to return the resource within.
         public AbstractResource next() {
              StandardSortElement ssa = items.get(position);                                             // Get a handle on the StandardSortElement     
              AbstractResource ar = ssa.getResource();                                                  // Now get the resource that's packaged up inside
              position++;                                                                                          // Increment the position
              return ar;                                                                                          // return the resource
         * Do not implement - mandatory interface implementation but not required here.
         public void remove() {
              // TODO Auto-generated method stub
    }This is the code taken from the JUnit test class
         * This iterator also has an interal child iterator. Check this works as expected
         @Test
         public void testChildIterator() {
              Iterator<AbstractResource> iterator = new StandardSortIterator(items);
              Integer i = 0;
              while (iterator.hasNext()) {
                   AbstractResource abstractResource = (AbstractResource)iterator.next();
                    if (i.equals(0)) {
                         // The first element should contain children - check it works
                         Iterator<BookingInterface> childIterator = iterator.createChildIterator(); // ERROR OCCURS HERE
                   i++;               
              assertTrue(i.equals(items.size()));
         /************************************************************************************/Thank you in advance for any help you can provide!
    Paul

    Your unit test is coded against the Iterator interface, not your SortIteratorInterface, which is where the createChildIterator method is defined. You need to use a reference to a SortIteratorInterface, not an Iterator. Incidentally, when defining an interface, it's unnecessary to declare the methods as public and abstract. They're implicitly that anyway

  • Iteration problem in script.

    Hi Experts,
       I have one Main window , footer window and logo windows in my script.But eventhough the WRITE FORMS are in same loop,
    in the first iteraion it is going only to the main window .So the first page Footer contains the second iteration value and so on.Please help me to solve this.
    I want to print the first iteration value in the first page footer.
    Regards,
    Sreeja

    Hi sreeja,
    Why dont you loop and when using write form, specify the window name.
    try this.
    loop at itab into wa.
    call function 'Write_form'
    importing
    window = 'window name XXX'
    call function 'Write_form'
    importing
    window = 'window name YYY'
    call function 'Write_form'
    importing
    window = 'window name ZZZ'
    endloop.  
    Blacky

  • Need help in iteration problem

    i have a question that requires to use iteration ("for" repetition ) and it inquires to enter each day's cost for a whole week and then calculate and display the total week's cost.
    can anyone help me with this? cause i've tried everything i know.

    dunno, i dont think it is cause the total is unknown
    and it is what i want to getof course the total is unknown. that's what your program does, finds it out. forget computers for a minute. how would you do this with a pen and paper? you'd start off not knowing the total, and ask questions until you had it, right? like
    "what were mondays takings?" "oh, 50"
    "ok,what were tuesdays?" "um, 102"
    "and wednesdays?" "200"
    and you'd add the latest answer to your running total. same thing here

  • Need Help With Iteration Problem

    So I recently decided I would try and make a program to help me edit my mp3 ID3 tags. I'm relatively new to Java but can usualy figure things out on my own. My code is rarely efficient but it gets the job done. So here's the deal. I got this package from ID3.org and started messing around with it. I can get it to edit the tags but not with an iteration. Here's my code:
    import javax.swing.*;
    import de.vdheide.mp3.*;
    import java.io.*;
    class ID3TagEdit {
         public static void main(String args[]) {
              String dir = chooseDir();
              String[] fileList = makeList(dir);
              String filename = "";
              for(int i = 0; fileList[i] != "null"; i++) {
                   try {
                        filename = dir + "\\" + fileList;
                        MP3File currentFile = new MP3File(filename);
                        TagContent tc = currentFile.getArtist();
                        tc.setContent("TEST");
                        currentFile.setArtist(tc);
                        currentFile.update();
                   catch(IOException e) {
                        System.out.println("Error 101");
                   catch(FrameDamagedException e) {
                        System.out.println("Error 102");
                   catch(NoMP3FrameException e) {
                        System.out.println("Error 103");
                   catch(TagFormatException e) {
                        System.out.println("Error 104");
                   catch(ID3Exception e) {
                        System.out.println("Error 105");
                   catch(ID3v2WrongCRCException e) {
                        System.out.println("Error 106");
                   catch(ID3v2Exception e) {
                        System.out.println("Error 107");
         public static String chooseDir() {
              String FolderPath = "";
              try {
                   JFileChooser chooser = new JFileChooser();
                   chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                   int returnVal = chooser.showOpenDialog(null);
                   FolderPath = chooser.getSelectedFile().getPath();
              catch(IllegalArgumentException e) {
                   System.out.println("Error 201");
              return FolderPath;
         public static String[] makeList(String dir) {
              File directory = new File(dir);
              String[] fileList = directory.list();
              return fileList;
    If I don't iterate it then it will work. If I omit the 'for' loop and change the code to this:
                        filename = dir + "\\" + fileList[3];
                        MP3File currentFile = new MP3File(filename);
                        TagContent tc = currentFile.getArtist();
                        tc.setContent("TEST");
                        currentFile.setArtist(tc);
                        currentFile.update();
    It works just fine. Any suggestions on what I'm doing wrong?

    If I don't iterate it then it will work. If I omit
    the 'for' loop and change the code to this:
    It works just fine. Any suggestions on what I'm
    doing wrong?You said
    without loop it works just fine.Then what's the wrong?
    If you don't use loop then your fileList may not be null.And then your program'll be in infinite loop.

  • Vector iteration problem

    hi all,
    This vector thing still has me off balance. Why does the following code throw an error?
    Enumeration enum = messageBodies.elements();
    int i = 0;
    while(enum.hasMoreElements()) {
    if(rowWasDeleted.elementAt(i).equals("true")) {
    messageBodies.removeElementAt(i);
    i++;
    System.out.println(messageBodies.size());
    I want to remove the messageBody that corresponds with a true value stored in rowWasDeleted. Can't seem to do it tho :-)

    You're not allowed to remove elements while enumerating them. Here's how you should do it.
    List list = new ArrayList();
    Iterator i = list.iterator();
    while (i.hasNext()) {
         Object o = i.next();
         if (/*condition*/) {
              i.remove();
    }

  • XQuery Iteration Problem

    Hey guys,
    I am using XQuery in PL-SQL to output data from a single table to an xml document on Oracle 10g. My problem is that I want to include a rowcount for each row in the XML document but my row count stays on "1" for every record and I dont know why. I have also tried using Oracle ROWNUM, but it seems XQuery does not like that at all. Here is the code:
    SELECT XMLQuery(
    '<requests>
    {let $i := 0
         for $row in ora:view("IT02M_VIS_REQUEST")
         let $req_no := $row/ROW/REQUEST_NO/text(),
             $req_date := $row/ROW/REQUEST_DATE,
             $req_name := $row/ROW/REQUESTER_NAME/text(),
             $i := $i + 1
         order by $req_no
         return
            <request rec_cnt="{$i}">
    <req_no>{$req_no}</req_no>
    <req_date>{$req_date/text()}</req_date>
    <req_name>{$req_name}</req_name>
    </request>}
    </requests>' RETURNING CONTENT)
    FROM dual;
    I want the variable $i to increment , but it does not.
    Any help please.

    I found the answer so I thought I'd share.
    The solution I needed involved appending items to a dictionary object during a for loop:
    myDict = {}
    for value in results:
    document = value.asDocument()
    name = document.getName()
    content = value.asString()
    myDict[name] = content
    return render_to_response('gutorglyn/searchResults.html', {'searchHits': hitList'})
    in the Django template you iterate through the dictionary like this:
    {% for name,content in searchHits.items%}
    {{content}}
    {{name}}
    {% endfor %}
    hope this helps someone out in the future
    regards

  • Iteration problem in ref cursor

    hi all
    declare
    type ref_cur is ref cursor;
    p_ref_cur ref_cur;
    type namelist is table of varchar2(10);
    type address is table of varchar2(20);
    p_namelist namelist;
    p_address address;
    begin
    open p_ref_cur for 'select emp_code,EMP_ADDR from emp_det_bak';
    fetch p_ref_cur bulk collect into p_namelist,p_address;
    for i in p_ref_cur
    loop
    dbms_output.put_line('this is for testing '||p_ref_cur(i));
    end loop;
    end;
    i found error like following--
    ERROR at line 11:
    ORA-06550: line 11, column 10:
    PLS-00221: 'P_REF_CUR' is not a procedure or is undefined
    ORA-06550: line 11, column 1:
    PL/SQL: Statement ignored
    if i use
    for i in p_ref_cur.first..p_ref_cur.last
    i got error message like --
    Invalid reference to variable 'P_REF_CUR'
    can anyone pls tell me what wrong i'm doing and if i want to iterate through will i use
    like--while(p_ref_cur.next) loop
    please suggest me.
    Message was edited by:
    p.bhaskar

    > please suggest me.
    Well, there is a fairly easy way to create a refcursor with the ability to loop through the columns of the cursor - without knowing what the columns are.
    However, this is not always an ideal approach. It uses VARCHAR2 as the data type for all columns and requires the source SQL to to construct a collection.
    Here's a brief example of this approach:
    SQL> create or replace type TColumns as table of varchar2(4000);
    2 /
    Type created.
    SQL>
    SQL> create or replace procedure DisplaySQL( sqlStatement varchar2 ) is
    2 c SYS_REFCURSOR;
    3 colList TColumns;
    4 rowCnt integer := 0;
    5 begin
    6 open c for sqlStatement;
    7
    8 loop
    9 fetch c into colList;
    10 exit when c%NOTFOUND;
    11
    12 rowCnt := rowCnt + 1;
    13
    14 W( '****************' ); -- W = DBMS_OUTPUT.put_line
    15 W( 'row: '||rowCnt );
    16 W( 'columns: '||colList.Count );
    17
    18 for i in 1..colList.Count
    19 loop
    20 W( 'column='||i||' value='||colList(i) );
    21 end loop;
    22 end loop;
    23
    24 W( '****************' );
    25 close c;
    26 end;
    27 /
    Procedure created.
    SQL>
    SQL>
    SQL> var SQL varchar2(4000);
    SQL>
    SQL> exec :SQL := 'select TColumns(created, object_type, object_name) from ALL_OBJECTS where rownum = 1';
    PL/SQL procedure successfully completed.
    SQL> exec DisplaySQL( :SQL )
    row: 1
    columns: 3
    column=1 value=2005/07/21 19:04:20
    column=2 value=TABLE
    column=3 value=CON$
    PL/SQL procedure successfully completed.
    SQL>
    SQL> exec :SQL := 'select TColumns(created, object_type, object_name) from
    ALL_OBJECTS where rownum = 1 UNION ALL select TColumns(dummy,SYSDATE) from
    DUAL';
    PL/SQL procedure successfully completed.
    SQL> exec DisplaySQL( :SQL )
    row: 1
    columns: 3
    column=1 value=2005/07/21 19:04:20
    column=2 value=TABLE
    column=3 value=CON$
    row: 2
    columns: 2
    column=1 value=X
    column=2 value=2007/05/16 13:14:56
    PL/SQL procedure successfully completed.
    SQL>

  • Sync Mode Immediate, create row causes iterator sync problems

    Hi,
    I'm building an application for a client and in that I've got a master detail ADF data page.
    The 'master' data is user details for the application and the 'detail' data is the various access privileges a user has related to different countries, i.e. update privilege for UK data, read access for Swedish data etc. etc.
    My page consists of a summary of master details (master iterator) in read only fields, a grid of detail records (detail iterator) and for each row in the grid, a 'select' link is provided which when selected, populates an input form on the same page with the details for that row (via setCurrentRowWithKey). The user can then update the details of the row and save.
    Problem I have is when a New detail record is created.
    The user presses a 'New' button (bound to Create action) which sets up the input form for a new detail record. The user enters the new details and presses 'Save' (bound to Commit action). Saving causes the detail grid to refresh (row position moves to 1st row in grid), showing the newly inserted record, however the input form itself on the page still contains the details of the inserted row.
    So if the record I insert should be displayed 3rd in the grid (due to an Order by I have on the VO), it does show up as 3rd. However, if I select the 1st record on the grid, the data for the 3rd is displayed in the input form, if I select the 2nd record on the grid, the data for the 2nd is displayed, if I select the 3rd record on the grid, the data for the 3rd is displayed again and so on. Selecting the 1st record again still displays data for the 3rd record in the input form.
    Somewhere the iterator is getting messed up.
    I always refresh the query at the prepareModel phase but this doesn't fix the issue. I'm using the initializeModelForPage method that was demonstrated in ToyStore. In fact my application is built in the style of the helper functions that were provided with ToyStore (and are an excellent help!)
    Can anyone point me in the right direction to fix this problem?
    I'm using JDev 10.1.2.1 with immediate sync mode.
    Thanks,
    Paul.

    I thought I'd pinned this down to the fact that on the page where there is no iterator problems, the PK of the table is a sequence.
    When I select any row in the grid (via setCurrentRowWithKey) on that page, the rowKeyStr for each row never changes when the page is reloaded (which is what I would expect).
    On the page where there is an iterator problems, each time I selected a row on the grid via setCurrentRowWithKey, the page reloaded and the rowKeyStr for that row had now changed to something else.
    The table underlying this page had a VARCHAR2 primary key. Thinking this was the cause of the problem, I added a new PK based on a sequence and set the previous PK to a unique key only. I changed all the related entity, link and view objects to reflect this. Also made sure that the previous PK field was not selected as a 'Key Attribute' under the view object dialog box. I've gone through the definition of the entity object closely to make sure it reflects the format of the table it's based on.
    Still though on this one page, a select of a row via setCurrentRowWithKey results in a change of the rowKeyStr when the page reloads and also JBO-33035 errors (as I said, pages that do work based on sequence PK tables don't change the rowKeyStr when reloaded).
    Any ideas on this behaviour would be welcome. Could there be something still ‘hanging around’ in the entity or view object definitions that is causing this behaviour? I'm really up against it now on this one.

Maybe you are looking for

  • MOVED: Driver Stopped Responding MSI 290 Gaming Edition 4G

    This topic has been moved to GAMING Graphics Cards. https://forum-en.msi.com/index.php?topic=254075.0

  • Adobe Connect 8 - Recordings

    Hello, I need help understanding the Universal Voice Solution or a comparable substitute for a situation I am in with adobe connect 8.  I am trying to basically learn how I can sync up an audio recording from a teleconference with a web cast recordin

  • Shared variable question

    Post Author: despec CA Forum: General Hello to the forum once more,I am trying to use a shared variable as a "switch" in a sub report to either turn on/off suppression of a text label and the associated field.  If the user selects a "summary" report,

  • Application Module Nesting Performance

    I have multiple application modules and it is currently nested to one main application module.Due to the complexity of my logic, I would like to refactor it further but I cannot move it outside the root application module because the instance of the

  • Is anyone having trouble opening iTunes on their iPhone?

    For the past two days I have tried to open iTunes on my iPhone 5 and first it said it couldn't connect and now it crashes.