BufferedImages in a loop

Hello,
I have a directory with about 14 jpg's. What I'm trying to do is load each jpg, convert to a bufferedImage and store in an ArrayList.
Works first time, but if I try to repeat without restarting the app. " out of memory error".
Anyone have a clue where I'm messing this one up at?
try{
  for( int j = 1; j <= questionText.length; j++ ){
       String fileName =  j+".jpg" ;
      // setup the path and file name
       File checkForImage = new File( dir+fileName );
         if( checkForImage.exists() ){
             // if the file exists create image icon of file
                 Image inImage = null;
                 inImage = new ImageIcon( dir+fileName ).getImage();
             // load the image with media tracker
                 MediaTracker m = null;
                 m = new MediaTracker(this);
                 m.addImage(inImage, 1 );
                 m.waitForID(1);
             // create a buffered image object and draw it
                 BufferedImage bi = null;
                 bi = new BufferedImage(inImage.getWidth(this),
                           inImage.getHeight(this),    BufferedImage.TYPE_INT_RGB);
                 Graphics2D biContext = bi.createGraphics();
                 biContext.drawImage(inImage, 0, 0, this);
              // add the image to the array list
                 imageList.add( bi );
                 bi.flush();
         else
             imageList.add( null );
           }// close for loop    
     catch ( Exception e ){e.printStackTrace();}
        

No good still crashed.
I tried creating the bufferedImage outside the loop,
bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
for(;;){
..... snip( see above )
Graphics 2D biContext = bi.createGraphics
biContext.drawImage(inImage, 0, 0, this);
...snip( see above )
imageList.add(bi);// all images are the same
it doesn't crash but all the images are the same( the last image read in ) when I dump it out to the directory.

Similar Messages

  • Color spaces problem

    Hi guys, i try to make a program that would let me choose a color, then modify some images i need using the color i choose. so i have an image, 12x12 pixels, casted to a BufferedImage. I loop through each pixel (counters x and y), executing:
    mybufferedimage.setRGB(x,y,mycolor.getRGB());
    sadly, the image i gat is not at all a square of my specified color, instead it is some other color (i noticed a similarity between my color's brightness and the colour that got on the image, but i'm not sure it has any relevance). I'm thinking this may be due to differences in Color Spaces (hence the title of this topic) but i am not sure.
    so my question is this:
    I have myColor and myBufferedImage. How do i set some (any) pixel(s) in myBufferedImage to be of the same color as myColor? And please explain (if you can) why my variant doesn't work.
    thanks.

    Teodor.Sandu wrote:
    Hi guys, i try to make a program that would let me choose a color, then modify some images i need using the color i choose. so i have an image, 12x12 pixels, casted to a BufferedImage. Where does this image come from? What does calling getType() on the BufferedImage return?
    I loop through each pixel (counters x and y), executing:
    mybufferedimage.setRGB(x,y,mycolor.getRGB());How is 'myColor' created?
    Post an SSCCE:
    http://www.physci.org/codes/sscce.html
    Jim S.

  • Image processing with BLOBS: how to write BufferedImage to a BLOB

    Hi everybody - thanks in advance for any input on that topic.
    I'm doing image processing using AWT and 2D. Images are stored in a RDBMS as BLOB Type, which I get using JDBC and convert to a BufferedImage using a JDBCImageDecoder.
    Now, I have my BufferedImage and I can process them using the appropriate filters (ConvolveOp e.g.)
    Writing the BufferedImages to disk or display on screen is easy. But I can't get to write them to a BLOB Object. Any Hint ?
    (Of course, I'm speaking of oracle.sql.BLOB objects, not java.sql.Blob).
    Thanks and have a nice day

    Billy,
    Thank you for your answer. I have two questions.
    First what that means "Bob's your uncle ?" I'm a french man, not used to english special sentences ou jargon. Would enjoy to know !
    Second, I have created a PL/SQL procedure to update my table. I face a problem.
    I want to initialize b_lob with the img_blob value but I get an error : "ORA-22922: nonexistent LOB value". WHere do my error comes from ? I am fairly new in this stuff of BLOB.
    Below my procedure.
    Thank for your kind help.
    Christian.
    create or replace
    procedure insert_img as
    f_lob bfile;
    b_lob blob;
    loops number default 0 ;
    lines number default 0;
    stmt varchar2(4000);
    cursor c1 is select img_blob, file_name, pk from photos FOR UPDATE ;
    begin
    NULL;
    dbms_output.enable(900000);
    stmt := 'SELECT COUNT(*) FROM PHOTOS';
    EXECUTE IMMEDIATE stmt INTO LINES ;
    for ligne in c1 loop
    exit when loops >= lines ;
    loops := loops+1;
    update photos set img_blob= empty_blob() where CURRENT OF C1;
    -- return img_blob into b_lob;
    b_lob := ligne.img_blob ;
    f_lob := bfilename( 'MY_FILES', ligne.file_name );
    IF (DBMS_LOB.FILEEXISTS(f_lob) != 0)
    THEN
          DBMS_OUTPUT.PUT_LINE('BFILE exist: '|| ligne.file_name || ', ligne :'|| ligne.pk);
          dbms_lob.fileopen(f_lob, dbms_lob.file_readonly);
          dbms_lob.loadfromfile( b_lob, f_lob, dbms_lob.getlength(f_lob) );
          dbms_lob.fileclose(f_lob);
          dbms_output.put_line('ligne.pk :' || ligne.pk || ', lines : ' || lines || ', loops ' || loops);
      ELSE
        DBMS_OUTPUT.PUT_LINE('BFILE does not exist: '|| ligne.file_name || ', ligne :'|| ligne.pk);
      END IF;
    end loop;
    commit;
    end insert_img;

  • BufferedImage causing OutOfMemoryError not getting GC'd

    I'm writing a photo library application just for practice. I'm trying to display all the jpegs in an album by displaying thumbnails of them as ImageIcons in JLabels on a JFrame.
    To get the images I use ImageIO.read(File) into a BufferedImage. Then using Image.getScaledInstance I pass the resized image to a new ImageIcon which is added to the JLabel. This all happens in a final class ThumbDisplay, method showPic which returns the JLabel.
    I call ThumbDisplay.showPic(File) in a loop, and it can read about 5 files before throwing an OutOfMemoryError. I have been able to successfully display no more than 4 images. Most of my images were taken on my digital camera and are around 2560X1920.
    I read a bit about the java heap space and I understand how 5 BufferedImages of that size open at once can easily eat up memory. But the code looks to me that any instantiated BufferedImages would be GC'd as soon as the showPic method returned the JLabel. JHAT proved otherwise and there were still 5 instances of BufferedImage when I got the OutOfMemoryError.
    So, the following is my example code block and the StackTrace. No extra stuff required. Just throw about 10 extra large jpegs in whatever path you choose to put in 'File directory' on line 9, compile and run. I'd really appreciate some help on this. I've searched countless message boards for that error and found many similar topics but ZERO answers. Can someone tell me why these aren't getting GC'd?
    code:
    1. import javax.swing.*; 
       2. import java.awt.image.*; 
       3. import javax.imageio.*; 
       4. import java.awt.*; 
       5. import java.io.*; 
       6.  
       7. public class ThumbTest{ 
       8.     public static void main(String args[]){ 
       9.         File directory = new File("c:\\pictemp\\"); 
      10.         File[] files = directory.listFiles(); 
      11.         JFrame jf = new JFrame(); 
      12.         jf.setSize(1000,1000); 
      13.         jf.setLayout(new GridLayout(10,10,15,15)); 
      14.         for(File file : files) 
      15.             jf.add(ThumbDisplay.showPic(file)); 
      16.          
      17.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      18.         jf.setVisible(true); 
      19.  
      20.  
      21.     } 
      22. } 
      23.  
      24. final class ThumbDisplay{ 
      25.      
      26.     public static JLabel showPic(File f){ 
      27.         BufferedImage img = null; 
      28.         try{ 
      29.             img = ImageIO.read(f); 
      30.         }catch (IOException e){ 
      31.             e.printStackTrace(); 
      32.         } 
      33.         if(img != null){ 
      34.             float ratio = 100 / (float) img.getHeight(); 
      35.             int w = Math.round((float)img.getWidth() * ratio); 
      36.             int h = Math.round((float)img.getHeight() * ratio); 
      37.             return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
      38.         } else 
      39.             return new JLabel("no image"); 
      40.     } 
      41. }exception:
       1. D:\java\Projects\PhotoLibrary>java ThumbTest 
       2. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 
       3.         at java.awt.image.DataBufferByte.<init>(Unknown Source) 
       4.         at java.awt.image.ComponentSampleModel.createDataBuffer(Unknown Source) 
       5.         at java.awt.image.Raster.createWritableRaster(Unknown Source) 
       6.         at javax.imageio.ImageTypeSpecifier.createBufferedImage(Unknown Source) 
       7.         at javax.imageio.ImageReader.getDestination(Unknown Source) 
       8.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Sou 
       9. rce) 
      10.         at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source) 
      11.         at javax.imageio.ImageIO.read(Unknown Source) 
      12.         at javax.imageio.ImageIO.read(Unknown Source) 
      13.         at ThumbDisplay.showPic(ThumbTest.java:29) 
      14.         at ThumbTest.main(ThumbTest.java:15) 

    sjasja wrote:
    ImageIO.read() does not cache images. Run ImageIO.read() in a loop for a large image. No OOME.
    Run the OP's original program under hprof. See in hprof's output how the original image data are retained. Gives an OOME, and hprof's output shows where the memory goes.
    After creating a resized image with Image.getScaledInstance(), make a copy of the resized image and discard the first resized image. (Create a BufferedImage, get a Graphics2D, and blit with g.drawImage()). Discarding the resized image will also make the pointer to the original large image go away, allowing GC. No OOME.
    In the OP's program, edit like so:
    // return new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT))); 
    new JLabel(new ImageIcon(img.getScaledInstance(w,h,Image.SCALE_DEFAULT)));
    return new JLabel("yes image");You are now doing all the image loading and resizing the original program does. But because the JLabel is discarded, the pointer to the resized image is discarded, thus the pointer to the original image is discarded, and everything can be GCd. No OOME.
    If you want to see how the scaled image retains a pointer to the original image, see the interaction of Image.getScaledImage(), BufferedImage.getSource(), java.awt.image.FilteredImageSource, sun.awt.image.OffScreenImageSource, and sun.awt.image.ToolkitImage.
    By these experiments, in a reply above, I guesstimated: "As far as I can figure out, Image.getScaledInstance() keeps a pointer to the original image."
    Yes, getScaledInstance() is somewhat slow. Here is the FAQ entry for a better way to resize an image: http://java.sun.com/products/java-media/2D/reference/faqs/index.html#Q_How_do_I_create_a_resized_copy
    I have a problem with this because it should mean that the code fragment I posted in reply #5 should make no difference but I can load over a thousand images using it whereas the original code allowed me to load only 30 or so.
    I can see how creating a buffered image from the scaled image might help since discarding the scaled image will discard any reference to the original image stored in the scaled image.

  • BufferedImage Problem

    This is kind of difficult to explain, but I'll do my best. It's a simple problem though.
    So I have a class, let's call it ImagePanel. Quite simply, it's a panel that loads an image and then loads a BufferedImage from that image. It uses MediaTracker and the waitForID function to allow the image to load before drawing it to the panel.
    That's fine and dandy. Works like a charm.
    Now in this same class, I have a function that returns the BufferedImage, allowing it to be passed to other classes. The code is simply "return bImage;"
    Now in one of my OTHER classes, it needs this BufferedImage to be passed into its constructor. This is done immediately at the beginning of the program. This is where my problem lied.
    The BufferedImage would not load quick enough to pass it into the constructor of my other class, so it kept passing a null BufferedImage rather than the actual image.
    Through trial and error, I fixed this problem with the following code:
    BufferedImage bImage = ImagePanel.getBufferedImage();
              while (bImage == null)
                   try
                        Thread.sleep(10); // Pause for a short moment to give bImage time to load
                   catch (Exception e)
                        JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
                   bImage = mapPanel.getBufferedImage(); // Try again
              }So if I slap a main function into the same class containing the code above, and create an instance of the class, and run it, it works fine, after a few seconds of loading (very inefficient program but that does not concern me for this project)
    Now the main problem, and the reason I created this thread, is that when I create an instance of this class in ANOTHER class, it gets caught in an infinite loop at the above code.
    However once again, if I simply make an instance of it in THE SAME CLASS, it works fine. What gives?

    Alright, now I'm really confused. What would I need to change in the following class to change over to ImageIO?
    I appreciate the help, I'm really frusterated at the moment.
    public class ImagePanel extends JPanel
         private BufferedImage bImageEditable, bImageConstant;
         private Image image;
         private int id = 0;
         private boolean panelSized = false;
         public ImagePanel(String file)
              loadMap(file);
         public void loadMap(String file)
              Toolkit tk = Toolkit.getDefaultToolkit();
              image = tk.getImage(file);
              MediaTracker tracker = new MediaTracker(this);
              tracker.addImage(image,id);
              try      
                   tracker.waitForID(id);
              catch (InterruptedException ie)
                   JOptionPane.showMessageDialog(null, "Error: " + ie.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
         public void scaleImage(int w, int h)
              image = image.getScaledInstance(w,h,Image.SCALE_DEFAULT);
              MediaTracker tracker = new MediaTracker(this);
              tracker.addImage(image, id);
              try
                   tracker.waitForID(id);
              catch (InterruptedException ie)
                   JOptionPane.showMessageDialog(null, "Error: " + ie.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
         public void loadBImage()
              // Load editable image
              bImageEditable = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
              Graphics bImageEditableG = bImageEditable.getGraphics();
              bImageEditableG.drawImage(image, 0,0,null, null);
              // Load constant image
              bImageConstant = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
              Graphics bImageConstantG = bImageConstant.getGraphics();
              bImageConstantG.drawImage(image, 0,0,null, null);
         public BufferedImage getBufferedImage()
              return bImageConstant;
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              if (!panelSized)
                   scaleImage(getWidth(), getHeight());
                   loadBImage();
                   panelSized = true;
              g.drawImage(bImageEditable, 0, 0, image.getWidth(null), image.getHeight(null), null);
              g.drawString(territoryName, 10, getHeight() - 10);
    }

  • Setting the color of individual pixels in a bufferedimage

    i am trying to set the color of each pixel in a loop as follows:-
    BufferedImage bi=new BufferedImage(w,h,BufferedImage.TYPE-INT_RGB);
    for(int j=0;j<h;j++){
    for(int i=0;i<w;i++){
    pixel=translate(i,j);
    clr=findcolor(pixel);
    if(clr==-1){
    bi.setRGB(i,j,0);
    else
    bi.setRGB(i,j,clr);
    findcolor() function just returns an int, so how do take this integer value and set the appropriate color?
    when i execute this code,in the PaintComponent method of a JPanel class, my entire panel becomes black, this is not because of my first "if" condition.i checked the return value of my findcolor function.
    However if i multiply the color value by a large number like 10000, then i get a few colors only(black,blue, green)
    So please let me know how i can get all colors, without having to multiply the value.

    What do the translate and findcolor methods do?

  • Creating BufferedImage from int[] (not RGB's)

    Hi,
    I have an int[] that contains how many intersections occur between each pixel and a series of overlapping rectangles. So the array would look like this:
    int [] intersections = { 0,1,1,1,1,0,2,4,4...etc} each number representing the number of times each pixel intersects a rectangle.
    What I would like to do is create a bufferedImage where each pixel in the image is a color based on the number of intersections from the array. 0 intersections is transparent, 1 intersection is a blue pixel , 2 intersections is green etc.
    I implemented it first looping through the array and painting a 1X1 rectangle colored according to the number of intersections but it is slow. Can I use a ColorModel for this (never used one)?. If so, what is a good method to convert these integers that represent the number of intersections to the corresponding color in a BufferedImage? The maximum number of intersections would be far fewer than 256, probably in the range of 10-50. I would also like to create the image in grayscale, the larger number of intersections getting darker and as hues of one color where an index of 0 would be transparent and as the number of intersections got larger the color gets darker. It all works the way I did it but it is way too slow. Will a ColorModel do transparent pixels? Is MemorySourceImage a good way to do this? Any ideas?
    Thanks very much!
    Paul

    You're more or less describing a IndexColorModel, except the data bank is usually a byte[]:
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    public class IndexColorModelTest {
        public static void main(String[] args) {
            int w = 300, h = 200;
            BufferedImage bi = createImage(w, h, createData(w, h));
            JLabel label = new JLabel(new ImageIcon(bi));
            label.setOpaque(true);
            label.setBackground(Color.RED);
            final JFrame f = new JFrame("IndexColorModelTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
        static byte[] createData(int w, int h) {
            byte[] data = new byte[w*h];
            new Random().nextBytes(data);
            return data;
        static BufferedImage createImage(int w, int h, byte[] data) {
            //create a color model with grays
            int SIZE = 256;
            byte[] gray = new byte[SIZE];
            for(int i=0; i<256; ++i)
                gray[i] = (byte) i;
            ColorModel cm = new IndexColorModel(8, SIZE, gray, gray, gray, 0); //0 is transparent pixel
            DataBuffer db = new DataBufferByte(data, w*h);
            WritableRaster r = Raster.createInterleavedRaster(db, w, h, w, 1, new int[]{0}, null);
            return new BufferedImage(cm, r, false, null);
    }

  • Why my gif cannot animate in for loop? Please help me.

    Hi all, i hope anyone could help me in this.
    My program contains a JLabel. Inside contains a ImageIcon thats holds an image.
    Initially, this label contains a jpg file. The picture shows on screen. Next i want to change to a gif file which can animate after activation of a button. But right after changing, i need to do a for loop for other activity maybe loop for 10000 times. But in the process of looping, my gif just cannot animate. Only after finished looping, then it animate. I used paintImmediately method btw. I cannot figure out the problem, can anyone help me?

    A for loop keeps the event dispatch thread busy with no opportunity to update the gui. Use a timer or thread to pause in your loop so the gui has a chance to be updated.
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class AnimationTiming implements Runnable {
        BufferedImage[] images;
        int index = 0;
        Thread thread;
        int delay = 150;
        boolean animating = false;
        JLabel label;
        public AnimationTiming(BufferedImage[] images) {
            this.images = images;
        public void run() {
            while(animating) {
                try {
                    Thread.sleep(delay);
                } catch(InterruptedException e) {
                    stop();
                index++;
                if(index > images.length-1)
                    index = 0;
                label.setIcon(new ImageIcon(images[index]));
        private void start() {
            if(!animating) {
                animating = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
        private void stop() {
            animating = false;
            if(thread != null)
                thread.interrupt();
            thread = null;
        private JScrollPane getContent() {
            label = new JLabel();
            label.setHorizontalAlignment(JLabel.CENTER);
            return new JScrollPane(label);
        public static void main(String[] args) throws IOException {
            String path = "images/doggy/T";
            BufferedImage[] images = new BufferedImage[14];
            for(int j = 0; j < images.length; j++)
                images[j] = ImageIO.read(new File(path + j + ".gif"));
            AnimationTiming test = new AnimationTiming(images);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getContent());
            f.setSize(300,300);
            f.setLocation(200,200);
            f.setVisible(true);
            test.start();
    }Doggy Images are from the examples page, down low.
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html

  • A problem with Threads and loops.

    Hi, I have some code that needs to be constantly running, like while(true)
          //code here
    }However, the code just checks to see if the user has input anything (and then if the user has, it goes to do some other stuff) so I don't need it constantly running and hogging up 98% of the CPU. So I made my class (which has the method that needs to be looped, call it ClassA) implement Runnable. Then I just added the method which needed to be looped into the public void run()
    I have another class which creates an instance of the above class (call it ClassB), and the main(String[] args) is in there.
    public static void main(String[] args)
              ClassA test = new ClassA();
              Thread thread = new Thread(test.getInstanceOfClassA());
              thread.start();
              while(true)
                           //I do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...) but I can't think of away to get it to run - sleep - run -sleep forever. Can someone help me?

    Hi, I have some code that needs to be constantly
    running, like while(true)
    //code here
    }However, the code just checks to see if the user has
    input anything (and then if the user has, it goes to
    do some other stuff) so I don't need it constantly
    running and hogging up 98% of the CPU. Where does the user input come from. Are you reading from an InputStream? If so, then your loop will be blocked anyway when reading from the InputStream until data is available. During that time, the loop will not consume processor cycles.
    public static void main(String[] args)
              ClassA test = new ClassA();
    Thread thread = new Thread(test.getInstanceOfClassA());I have never seen this idiom. If ClassA instanceof Runnable, you simply write new Thread(test).
              thread.start();
              while(true)
    //I do not know what to put
    do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...)Yeah, why would you want to call it more than once given that you have an infinite loop in ClassA.run()?
    Harald.
    Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

  • Previewing loops

    Have had no luck with PCs trying to do music recoding so I swithced over to Mac because I heard it so easy, seamless, and problem free. Now, on opening Garageband for the first time and trying to preview loops I get an error mesage that says: "the software instrument or apple loop selected is currently being installed. You have already initiated the installation of additional content for Garageband via Software update. For additional information please open the software update application." I have opened this application and nothing. I have now spent about two hours trying to fix this problem. Should I "convert back to PC, take this load of crap back to the store or is there something simple I am missing?

    I have found if you wait long enough, you will hear the file begin to play. Sometimes the delay can several seconds. Not acceptable IMO.

  • Adobe Cloud membership - I am stuck in the loop of Licensing VERY Frustrating!!!

    I have an Adobe Cloud membership - I am stuck in the loop of Licensing as well VERY Frustrating - I have a project due and have been troubleshooting for days -
    Un Installing - Re installing - NIGHTMARE  - Please someone help me!!! Thanks in advance -

    What happens when you enter your Adobe ID tied to your subscription?

  • Lock ups and sound looping!

    I remember reading something here about people having trouble with their systems locking up and then getting a loud static noise then a sound loop when playing games.
       I am getting this about 2-3 times a night now and it is driving me nuts, I do not have temp problems of any sort and I have all of the latest drivers for everything on my system.
      Any ideas?
    Specs in sig

    Set your PCI/AGP Freq to 66.66/33.33MHz.
    Increase your DDR Voltage to 2.7~2.8v.
    Check if you have any background programs causing all high CPU load times while gaming.

  • Help with if statement in cursor and for loop to get output

    I have the following cursor and and want to use if else statement to get the output. The cursor is working fine. What i need help with is how to use and if else statement to only get the folderrsn that have not been updated in the last 30 days. If you look at the talbe below my select statement is showing folderrs 291631 was updated only 4 days ago and folderrsn 322160 was also updated 4 days ago.
    I do not want these two to appear in my result set. So i need to use if else so that my result only shows all folderrsn that havenot been updated in the last 30 days.
    Here is my cursor:
    /*Cursor for Email procedure. It is working Shows userid and the string
    You need to update these folders*/
    DECLARE
    a_user varchar2(200) := null;
    v_assigneduser varchar2(20);
    v_folderrsn varchar2(200);
    v_emailaddress varchar2(60);
    v_subject varchar2(200);
    Cursor c IS
    SELECT assigneduser, vu.emailaddress, f.folderrsn, trunc(f.indate) AS "IN DATE",
    MAX (trunc(fpa.attemptdate)) AS "LAST UPDATE",
    trunc(sysdate) - MAX (trunc(fpa.attemptdate)) AS "DAYS PAST"
    --MAX (TRUNC (fpa.attemptdate)) - TRUNC (f.indate) AS "NUMBER OF DAYS"
    FROM folder f, folderprocess fp, validuser vu, folderprocessattempt fpa
    WHERE f.foldertype = 'HJ'
    AND f.statuscode NOT IN (20, 40)
    AND f.folderrsn = fp.folderrsn
    AND fp.processrsn = fpa.processrsn
    AND vu.userid = fp.assigneduser
    AND vu.statuscode = 1
    GROUP BY assigneduser, vu.emailaddress, f.folderrsn, f.indate
    ORDER BY fp.assigneduser;
    BEGIN
    FOR c1 IN c LOOP
    IF (c1.assigneduser = v_assigneduser) THEN
    dbms_output.put_line(' ' || c1.folderrsn);
    else
    dbms_output.put(c1.assigneduser ||': ' || 'Overdue Folders:You need to update these folders: Folderrsn: '||c1.folderrsn);
    END IF;
    a_user := c1.assigneduser;
    v_assigneduser := c1.assigneduser;
    v_folderrsn := c1.folderrsn;
    v_emailaddress := c1.emailaddress;
    v_subject := 'Subject: Project for';
    END LOOP;
    END;
    The reason I have included the folowing table is that I want you to see the output from the select statement. that way you can help me do the if statement in the above cursor so that the result will look like this:
    emailaddress
    Subject: 'Project for ' || V_email || 'not updated in the last 30 days'
    v_folderrsn
    v_folderrsn
    etc
    [email protected]......
    Subject: 'Project for: ' Jim...'not updated in the last 30 days'
    284087
    292709
    [email protected].....
    Subject: 'Project for: ' Kim...'not updated in the last 30 days'
    185083
    190121
    190132
    190133
    190159
    190237
    284109
    286647
    294631
    322922
    [email protected]....
    Subject: 'Project for: Joe...'not updated in the last 30 days'
    183332
    183336
    [email protected]......
    Subject: 'Project for: Sam...'not updated in the last 30 days'
    183876
    183877
    183879
    183880
    183881
    183882
    183883
    183884
    183886
    183887
    183888
    This table is to shwo you the select statement output. I want to eliminnate the two days that that are less than 30 days since the last update in the last column.
    Assigneduser....Email.........Folderrsn...........indate.............maxattemptdate...days past since last update
    JIM.........      jim@ aol.com.... 284087.............     9/28/2006.......10/5/2006...........690
    JIM.........      jim@ aol.com.... 292709.............     3/20/2007.......3/28/2007............516
    KIM.........      kim@ aol.com.... 185083.............     8/31/2004.......2/9/2006.............     928
    KIM...........kim@ aol.com.... 190121.............     2/9/2006.........2/9/2006.............928
    KIM...........kim@ aol.com.... 190132.............     2/9/2006.........2/9/2006.............928
    KIM...........kim@ aol.com.... 190133.............     2/9/2006.........2/9/2006.............928
    KIM...........kim@ aol.com.... 190159.............     2/13/2006.......2/14/2006............923
    KIM...........kim@ aol.com.... 190237.............     2/23/2006.......2/23/2006............914
    KIM...........kim@ aol.com.... 284109.............     9/28/2006.......9/28/2006............697
    KIM...........kim@ aol.com.... 286647.............     11/7/2006.......12/5/2006............629
    KIM...........kim@ aol.com.... 294631.............     4/2/2007.........3/4/2008.............174
    KIM...........kim@ aol.com.... 322922.............     7/29/2008.......7/29/2008............27
    JOE...........joe@ aol.com.... 183332.............     1/28/2004.......4/23/2004............1585
    JOE...........joe@ aol.com.... 183336.............     1/28/2004.......3/9/2004.............1630
    SAM...........sam@ aol.com....183876.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183877.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183879.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183880.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183881.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183882.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183883.............3/5/2004.........3/8/2004.............1631
    SAM...........sam@ aol.com....183884.............3/5/2004.........3/8/2004............     1631
    SAM...........sam@ aol.com....183886.............3/5/2004.........3/8/2004............     1631
    SAM...........sam@ aol.com....183887.............3/5/2004.........3/8/2004............     1631
    SAM...........sam@ aol.com....183888.............3/5/2004.........3/8/2004............     1631
    PAT...........pat@ aol.com.....291630.............2/23/2007.......7/8/2008............     48
    PAT...........pat@ aol.com.....313990.............2/27/2008.......7/28/2008............28
    NED...........ned@ aol.com.....190681.............4/4/2006........8/10/2006............746
    NED...........ned@ aol.com......95467.............6/14/2006.......11/6/2006............658
    NED...........ned@ aol.com......286688.............11/8/2006.......10/3/2007............327
    NED...........ned@ aol.com.....291631.............2/23/2007.......8/21/2008............4
    NED...........ned@ aol.com.....292111.............3/7/2007.........2/26/2008............181
    NED...........ned@ aol.com.....292410.............3/15/2007.......7/22/2008............34
    NED...........ned@ aol.com.....299410.............6/27/2007.......2/27/2008............180
    NED...........ned@ aol.com.....303790.............9/19/2007.......9/19/2007............341
    NED...........ned@ aol.com.....304268.............9/24/2007.......3/3/2008............     175
    NED...........ned@ aol.com.....308228.............12/6/2007.......12/6/2007............263
    NED...........ned@ aol.com.....316689.............3/19/2008.......3/19/2008............159
    NED...........ned@ aol.com.....316789.............3/20/2008.......3/20/2008............158
    NED...........ned@ aol.com.....317528.............3/25/2008.......3/25/2008............153
    NED...........ned@ aol.com.....321476.............6/4/2008.........6/17/2008............69
    NED...........ned@ aol.com.....322160.............7/3/2008.........8/21/2008............4
    MOE...........moe@ aol.com.....184169.............4/5/2004.......12/5/2006............629
    [email protected]/27/2004.......3/8/2004............1631
    How do I incorporate a if else statement in the above cursor so the two days less than 30 days since last update are not returned. I do not want to send email if the project have been updated within the last 30 days.
    Edited by: user4653174 on Aug 25, 2008 2:40 PM

    analytical functions: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/functions2a.htm#81409
    CASE
    http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/02_funds.htm#36899
    http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/04_struc.htm#5997
    Incorporating either of these into your query should assist you in returning the desired results.

  • Sy-tabix in loop : Doubt

    LOOP AT i_lfa1 INTO wa_lfa1 WHERE werks = space.       
       wf_tabix = sy-tabix.                                 
       APPEND wa_lfa1 TO i_lfa1_werks.                      
       DELETE i_lfa1 index wf_tabix.                        
    ENDLOOP.                                               
    in the above code the sy-tabix is always 2.
    what i want to know is if there is a where clause , should we not use the sy-tabix for deletion.

    >
    Keshav.T wrote:
    > May be ill  get something from sap help.
    Hello Keshav,
    As a matter of fact , I always do
    SAP says:
    If you delete the current line or lines in front of the current line, the internal loop counter is decreased by one with each deleted line. In the case of loops on index tables or if using a sorted key, this affects sy-tabix in the subsequent loop pass, and sy-tabix is decreased accordingly
    @Dzed: Hail SAP Help !!! Anyways this was common sense & i dont think SAP processor is dumb
    Cheers,
    Suhas
    Edited by: Suhas Saha on Jan 28, 2010 6:46 PM

  • Sy-tabix in relation to LOOP AT and READ TABLE

    Hi All,
    As per SAP documentation,
    1) While looping through an internal table (LOOP AT), sy-tabix contains the index number of current row(for standard and sorted tables)
    2)When successfully reading from an internal table(READ TABLE), sy-tabix is set to the index of the result row.
    But what happens when READ TABLE is used while looping through another internal table?
    i.e. Loop at TAB1...
    write sy-tabix.
    READ TABLE TAB2...
    write sy-tabix.
    endloop.
    If we are looping through 1st row of TAB1 and the result of read statement is found in 3rd row of TAB2, I expected that sy-tabix before READ would be 1 and after the READ be 3.
    But, I found that sy-tabix remains unchanged at 1. Can someone expalin why?
    Thanks,
    Jagan

    Hi
    If after reading the table TAB2 the system variable SY-TABIX has still the previous value, that menas the READ TABLE fails or it was read the first record of TAB2.
    After READ TABLE TAB2 try to check the SY-SUBRC:
    LOOP AT TAB1.
       WRITE: / 'TAB1 index:', SY-TABIX.
       READ TABLE TAB2 .........
       IF SY-SUBRC = 0.
         WRITE: 'TAB2 index:', SY-TABIX.
    Try this:
    DATA: BEGIN OF ITAB OCCURS 0,
            FIELD1,
          END   OF ITAB.
    DATA: BEGIN OF ITAB2 OCCURS 0,
            FIELD1,
          END   OF ITAB2.
    DATA: INDEX TYPE I.
    DO 10 TIMES.
      APPEND ITAB.
    ENDDO.
    DO 10 TIMES.
      APPEND ITAB2.
    ENDDO.
    LOOP AT ITAB.
      WRITE: / 'ITAB:', SY-TABIX.
      INDEX = SY-TABIX + 2.
      READ TABLE ITAB2 INDEX INDEX.
      IF SY-SUBRC = 0.
        WRITE:  'ITAB2:', SY-TABIX.
      ENDIF.
    ENDLOOP.
    Max

Maybe you are looking for