Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

Looping in Java code: URGENT

Hi,
I have written the following code which i am using in a mobile phone emulator to retrieve images from a webserver. The problem is the loop only iterates 4 or 5 times even though I've got the counter set so that it iterates while i < 100. Could anyone please look at my code and see where I might be going wrong??



import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.*;

/**
 * A MIDP application that fetches and displays  
 * an arbitrary image from the Web using the  
 * ImageAdapter servlet.
 */

public class ImageClient2 extends MIDlet
              implements CommandListener {

    // Adjust this URL appropriately for
    // the adapter

    // A default image to display...

   private static String defaultURL = "http://localhost:8080/AutoCapture/image.png";                              


    private Form mMainForm;
    private Display display;
    private Command exitCommand = new Command( "Exit", Command.EXIT, 1 );
    private Command okCommand   = new Command( "Back", Command.OK, 1 );
    private Command sendCommand = new Command( "Get", Command.OK, 1 );
    private Command continueCommand   = new Command( "Continue", Command.OK, 1 );
    private Command returnCommand = new Command( "Menu", Command.OK, 1 );
    private TextBox entryForm;
    private int     screenHeight;
    private int     screenWidth;
    private int     numColors;

    public ImageClient2(){
      
    mMainForm = new Form("Lab Camera");
    mMainForm.append(new StringItem(null, "To view the Lab Monitor click Continue. Press exit to return to the menu."));
    DateField date = new DateField("The current Date and Time is:", DateField.DATE_TIME);
    date.setDate(new Date());
    mMainForm.append(date);

    mMainForm.addCommand(continueCommand);
    mMainForm.addCommand(returnCommand);
 
    mMainForm.setCommandListener(this);
    }

    protected void destroyApp( boolean
      unconditional )
        throws MIDletStateChangeException {
        exitMIDlet();
    }

    protected void pauseApp(){
    }

    protected void startApp()
           throws MIDletStateChangeException {
        if( display == null ){ // first time called...
            initMIDlet();
        }
    }

    // First we display the dummy canvas so
    // we can get information about the display

    private void initMIDlet(){
        display = Display.getDisplay(this);
        display.setCurrent(mMainForm);
        entryForm = new EntryForm();
        display.setCurrent( new DummyCanvas() );
    }

    public void exitMIDlet(){
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d )
      {
            if ( c == returnCommand )
            {
                  exitMIDlet();
            }
            else if( c == continueCommand )
            {
                  display.setCurrent( entryForm );
              }
            else if( c == sendCommand )
            {      
                      StatusForm f = new StatusForm(entryForm.getString());
                      display.setCurrent( f );
                            f.start();
            }
            else if( c == okCommand )
            {  
                  display.setCurrent( entryForm );
              }
             else
            {
                  exitMIDlet();
              }
    }

    // A dummy canvas to get the size of
    // the screen

    class DummyCanvas extends Canvas {
        protected void paint( Graphics g ){
            screenHeight = getHeight();
            screenWidth  = getWidth();
            numColors    = display.numColors();

            // Go directly to the main screen

            display.setCurrent( mMainForm );
        }
    }

    // The text entry form...

    class EntryForm extends TextBox {
        EntryForm(){
            super( "Enter a URL", defaultURL,80, 0 );
            addCommand( exitCommand );
            addCommand( sendCommand );
            setCommandListener(ImageClient2.this );
        }
    }

    // Show the image...

    class ShowImage extends Canvas
 {
      private Image image;

      ShowImage( byte[] imageData )
      {
        image = Image.createImage( imageData,0,imageData.length );
            display.setCurrent( this );
            addCommand( okCommand );
            setCommandListener( ImageClient2.this );
        }

        protected void paint( Graphics g ){
            g.drawImage( image, 0, 0,g.TOP | g.LEFT );
        }

       
    }

   

    class StatusForm extends Form implements Runnable
 {
       private StringItem message;
        private byte[] data;
      String url = "";

        StatusForm( String url )
      {
            super( "" );
            this.url = url;
      }

        // Do the connection on a separate  
        // thread to keep the UI responsive...

        public void run(){
            HttpConnection conn = null;

           System.out.println("Obtaining HttpConnection object..." );


      for(int i = 1; i < 100; i++)
      {
            try {
                         conn = (HttpConnection)Connector.open("http://localhost:8080/AutoCapture/image" + i + ".png");
            
                      int rc = conn.getResponseCode();
                if( rc == HttpConnection.HTTP_OK ){
                  try {
                    DataInputStream din = new DataInputStream(conn.openInputStream());
             data = new byte[ (int)conn.getLength() ];
                        din.readFully( data );
                        din.close();

                    }
                    catch( IOException e )
                {}


                    new ShowImage( data );
                  
            
                } else {
                   System.out.println( "Unexpected return code: " + rc );
                      
                conn.close();
            }
            }
            catch( IOException e ){
          //      done( "Exception " + e + " trying to connect." );
            }
      }
      }

        // Starts the upload in the background...

        void start(){
            System.out.println( "Starting..." );

            Thread t = new Thread( this );
            try {
                t.start();
            }
            catch( Exception e ){
             //   done( "Exception " + e + " trying to start thread." );
            }
        }
     
    }
}


0
houlic
Asked:
houlic
  • 6
  • 5
  • 5
  • +1
1 Solution
 
CEHJCommented:
You're not doing yourself any favours at all by swallowing all the exceptions in your loop (and elsewhere for that matter). Print their stack traces and you might be surprised.
0
 
houlicAuthor Commented:
I don't understand what you mean. I'm not that advanced in Java Programming. Could you give me more information or show me how to change the code
0
 
TimYatesCommented:
Put a

  for( int i = 1 ; i < 100 ; i++ )
  {
    System.out.println( "Loop " + i ) ;

in your loop...

I reckon it's either locking on one of the images, or else an  Exception you don't catch is being thrown...

Try changing your:

 catch( IOException e ){
   //      done( "Exception " + e + " trying to connect." );
 }

to:

 catch( Exception e ){
   System.err.println( "******************In loop " + i ) ;
   e.printStackTrace() ;
 }
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
You may as well take it as a rule that you should NEVER have code like this:

>>

                   catch( IOException e )
              {}
>>

It will make bug tracing very difficult indeed. Always print the stack trace, preferably with a custom message before printing it.
0
 
houlicAuthor Commented:
I've changed my code as above and i'm getting the following error from the 6th loop onwards:
******************In loop 6

java.io.IOException: exceeded the configured maximum number of connections

     at com.sun.midp.io.j2me.http.StreamConnectionPool.createStreamConnectionElement(+114)

     at com.sun.midp.io.j2me.http.StreamConnectionPool.getConnection(+121)

     at com.sun.midp.io.j2me.http.Protocol.connect(+64)

     at com.sun.midp.io.kvem.http.Protocol.connect(+4)

     at com.sun.midp.io.j2me.http.Protocol.sendRequest(+90)

     at com.sun.midp.io.j2me.http.Protocol.getResponseCode(+5)

     at ImageClient2$StatusForm.run(+77)



Does this mean that I cannot connect to my server this many times? Is there any way I can connect to the server once and keep pulling back images without continuously connecting to the server?
0
 
houlicAuthor Commented:
I've changed my code as above and i'm getting the following error from the 6th loop onwards:
******************In loop 6

java.io.IOException: exceeded the configured maximum number of connections

     at com.sun.midp.io.j2me.http.StreamConnectionPool.createStreamConnectionElement(+114)

     at com.sun.midp.io.j2me.http.StreamConnectionPool.getConnection(+121)

     at com.sun.midp.io.j2me.http.Protocol.connect(+64)

     at com.sun.midp.io.kvem.http.Protocol.connect(+4)

     at com.sun.midp.io.j2me.http.Protocol.sendRequest(+90)

     at com.sun.midp.io.j2me.http.Protocol.getResponseCode(+5)

     at ImageClient2$StatusForm.run(+77)



Does this mean that I cannot connect to my server this many times? Is there any way I can connect to the server once and keep pulling back images without continuously connecting to the server?
0
 
houlicAuthor Commented:
I've changed my code as above and i'm getting the following error from the 6th loop onwards:
******************In loop 6

java.io.IOException: exceeded the configured maximum number of connections

     at com.sun.midp.io.j2me.http.StreamConnectionPool.createStreamConnectionElement(+114)

     at com.sun.midp.io.j2me.http.StreamConnectionPool.getConnection(+121)

     at com.sun.midp.io.j2me.http.Protocol.connect(+64)

     at com.sun.midp.io.kvem.http.Protocol.connect(+4)

     at com.sun.midp.io.j2me.http.Protocol.sendRequest(+90)

     at com.sun.midp.io.j2me.http.Protocol.getResponseCode(+5)

     at ImageClient2$StatusForm.run(+77)



Does this mean that I cannot connect to my server this many times? Is there any way I can connect to the server once and keep pulling back images without continuously connecting to the server?
0
 
CEHJCommented:
I can't read your code very well since you haven't indented it very well and this site using non-monospaced fonts doesn't help. Can you try and indent again and use the following convention, which will add clarity:

for () {
} // end for


if () {
}// end if
0
 
kaushikgmehtaCommented:
I think the problem is in u not closing the connection properly. U are closing the connection only in the else part of ur for loop which would mean that u close the connection only if it enters the else. Check out how many times does it enter else and also change ur code so that ur connection closes before it opens again.
0
 
TimYatesCommented:
Cool!

Change it all to:


for( int i = 1 ; i < 100 ; i++ )
{
  try
  {
    conn = ( HttpConnection )Connector.open( "http://localhost:8080/AutoCapture/image" + i + ".png" ) ;

    int rc = conn.getResponseCode() ;
    if( rc == HttpConnection.HTTP_OK )
    {
      try
      {
        DataInputStream din = new DataInputStream( conn.openInputStream() ) ;
        data = new byte[ ( int )conn.getLength() ] ;
        din.readFully( data ) ;
        din.close() ;

      }
      catch( IOException e )
      {}
      new ShowImage( data ) ;
    }
    else
    {
      System.out.println( "Unexpected return code: " + rc ) ;
    }
  }
  catch( IOException e )
  {
    //      done( "Exception " + e + " trying to connect." );
  }
  finally
  {
    try{ if( conn != null ) { conn.close() ; conn = null ; } } catch( IOException ex ) {}
  }
}


The "finally" block will MAKE SURE you close the connection each loop round..
0
 
CEHJCommented:
>>

     catch( IOException e )
     {}

>>

NO!
0
 
TimYatesCommented:
Oh yeah!

LOL!

Didn't see that one...
0
 
TimYatesCommented:
So...change your for loop to:

for( int i = 1 ; i < 100 ; i++ )
{
 try
 {
   conn = ( HttpConnection )Connector.open( "http://localhost:8080/AutoCapture/image" + i + ".png" ) ;

   int rc = conn.getResponseCode() ;
   if( rc == HttpConnection.HTTP_OK )
   {
     DataInputStream din = new DataInputStream( conn.openInputStream() ) ;
     data = new byte[ ( int )conn.getLength() ] ;
     din.readFully( data ) ;
     new ShowImage( data ) ;
   }
   else
   {
     System.out.println( "Unexpected return code: " + rc ) ;
   }
 }
 catch( IOException e )
 {
   //      done( "Exception " + e + " trying to connect." );
 }
 finally
 {
   try{ if( conn != null ) { conn.close() ; conn = null ; } } catch( IOException ex ) {}
 }
}

Thanks CEHJ :-)
0
 
CEHJCommented:
>>
  //      done( "Exception " + e + " trying to connect." );
>>

NO!
0
 
TimYatesCommented:
/me shrugs

Don't really matter...it will at least now loop through all 100 :-)
0
 
houlicAuthor Commented:
Great stuff TimYates. Thanks a lot.
0
 
houlicAuthor Commented:
Thanks a lot. Thats my project sorted.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 5
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now