?
Solved

Looping in Java code: URGENT

Posted on 2003-03-05
17
Medium Priority
?
243 Views
Last Modified: 2013-11-23
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
Comment
Question by:houlic
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 5
  • +1
17 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8070915
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
 

Author Comment

by:houlic
ID: 8070926
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
 
LVL 35

Expert Comment

by:TimYates
ID: 8070931
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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 86

Expert Comment

by:CEHJ
ID: 8070950
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
 

Author Comment

by:houlic
ID: 8070970
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
 

Author Comment

by:houlic
ID: 8070978
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
 

Author Comment

by:houlic
ID: 8070988
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 8071003
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
 

Expert Comment

by:kaushikgmehta
ID: 8071054
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
 
LVL 35

Expert Comment

by:TimYates
ID: 8071060
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 8071081
>>

     catch( IOException e )
     {}

>>

NO!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8071111
Oh yeah!

LOL!

Didn't see that one...
0
 
LVL 35

Accepted Solution

by:
TimYates earned 300 total points
ID: 8071455
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 8071467
>>
  //      done( "Exception " + e + " trying to connect." );
>>

NO!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8071657
/me shrugs

Don't really matter...it will at least now loop through all 100 :-)
0
 

Author Comment

by:houlic
ID: 8072204
Great stuff TimYates. Thanks a lot.
0
 

Author Comment

by:houlic
ID: 8072217
Thanks a lot. Thats my project sorted.
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses
Course of the Month13 days, 4 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question