×

Discussion Board

Results 1 to 9 of 9
  1. #1
    Registered User
    Join Date
    Jun 2010
    Location
    India
    Posts
    200

    J2ME Multithread concept for asyn call .. Download images

    hello friends,
    I'm making j2me application ..
    this application is network based app.

    concept is Download No of images & show on canvas...

    So i need to download No of images due to this...my app get stuck till all images download...
    after download images application works fine....
    i know he reason behind it Its synchronous ...

    i used thread concept for same ...& i got solution ...

    Now my problem is ... I've lots of classess & those classes containing lots of images need to download ....
    So should i use separate thread for each class.......Is that create any problem with my application ...


    Please help me for this problem OR suggest me any other way for same.........
    thanks & Regards.
    Nilesh

  2. #2
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: J2ME Multithread concept for asyn call .. Download images

    Hi nyerunkar,

    In a multi-thread approach, each thread consumes processing power and memory, so if you have a lot of connection operations, and therefore a lot of threads running at the same time, you should expect a reduction of the available memory during your multi-thread connections. The only reason I would assume that you would try that, is to enhance performance, but on the down side, if your application is to run on devices with very limited resources, you might exhaust the memory and force the application to close.

    If you are happy with the time it takes to load all images while placing all the connections in a single thread, that should be a safer path, as your application is still responsive to the user's input while the image downloading takes place (though each connection won't initiate before the completion of the previous one). You should be careful though with how you design the UI and the interaction with the user, because if you allow the end user to keep pressing the connection button, after the initial try, you will end up creating a new thread each time the button is pressed.

    If you are unhappy with the time it takes to load all images in a single thread, you could try to place each connection on a separate thread or group the connections within a small number of threads. In this case, and depending on your application/what classes it uses, you have to be very careful, on how you access certain objects such as Player, DataSource, Controls, or when painting/repainting the canvas, as those operations need to be properly synchronized in order to get the appropriate result:

    http://library.developer.nokia.com/i...973C19D6E.html

    The Energy profiler is an application that lets you monitor how your midlet consumes your device's resources, so you might want to use that:
    http://www.developer.nokia.com/info/..._Profiler.html

  3. #3
    Registered User
    Join Date
    Jun 2010
    Location
    India
    Posts
    200

    Re: J2ME Multithread concept for asyn call .. Download images

    thnx for reply...............you have any sample thread for same problem ..?.
    thanks & Regards.
    Nilesh

  4. #4
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: J2ME Multithread concept for asyn call .. Download images

    Hi nyerunkar,

    This is a very basic example where all the http connection requests are placed in on thread.
    Code:
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    
    
    public class MultipleConnections extends MIDlet implements Runnable, CommandListener {
    	Thread t;
    	Form f;
    	Command infoCommand=new Command("Info",Command.OK,1);
    	Command exitCommand=new Command("Exit",Command.EXIT,0);
    	protected void destroyApp(boolean unconditional)
    			throws MIDletStateChangeException {}
    
    	protected void pauseApp() {	}
    
    	protected void startApp() throws MIDletStateChangeException {
    		t=new Thread(this);
    		t.start();
    		f=new Form("Multi Connections");
    		f.addCommand(infoCommand);
    		f.addCommand(exitCommand);
    		f.setCommandListener(this);
    		Display.getDisplay(this).setCurrent(f);
    	}
    	
    	private String connect(String targetUrl) 
    	{
    		String response="";
    		HttpConnection connection = null;
    		InputStream inputstream = null;
    	    try
    	    {
    	    	connection = (HttpConnection) Connector.open(targetUrl);
    	        //HTTP Request
    	        connection.setRequestMethod(HttpConnection.GET);
    	        // HTTP Response
    	        if (connection.getResponseCode() == HttpConnection.HTTP_OK)
    	        {	          
    	        	inputstream = connection.openInputStream();
    	        	int length = (int) connection.getLength();
    	        	if (length != -1)
    	        	{
    	        		byte incomingData[] = new byte[length];
    	        		inputstream.read(incomingData);
    	        		response = new String(incomingData);
    	        	}
    	        	else  
    	        	{
    	        		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    	        		int ch;
    	        		while ((ch = inputstream.read()) != -1)
    	        		{
    	        			bytestream.write(ch);
    	        		}
    	        		response = new String(bytestream.toByteArray());
    	        		bytestream.close();	            
    	        	}	          
    	        }
    	    }	
    	    catch(IOException error)
    	    {
    	       System.out.println("Caught IOException: " + error.toString());	       
    	    }
    	    finally
    	    {
    	    	if (inputstream!= null)
    	        {
    	          try 
    	          { 
    	            inputstream.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	        if (connection != null)
    	        {
    	          try
    	          {
    	             connection.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	    }
    	    return response;		
    	}
    
    	public void run() {
    		String fetchpage1=connect("http://www.w3.org");
    		f.append("Fetching 1 completed!\n");
    		String fetchpage2=connect("http://www.internet.org");
    		f.append("Fetching 2 completed!");
    	}
    
    	public void commandAction(Command arg0, Displayable arg1) {
    		if(arg0==exitCommand)
    		{
    			notifyDestroyed();
    		}
    		if(arg0==infoCommand)
    		{
    			f.append("App is responsive\n");
    		}
    		
    	}
    }

  5. #5
    Registered User
    Join Date
    Jun 2010
    Location
    India
    Posts
    200

    Re: J2ME Multithread concept for asyn call .. Download images

    hey thanks for reply,,,,
    But iknow this ..steps.....

    i want make generic class for Download multiple images.....
    this class method is accessible from another class.....



    Quote Originally Posted by skalogir View Post
    Hi nyerunkar,

    This is a very basic example where all the http connection requests are placed in on thread.
    Code:
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    
    
    public class MultipleConnections extends MIDlet implements Runnable, CommandListener {
    	Thread t;
    	Form f;
    	Command infoCommand=new Command("Info",Command.OK,1);
    	Command exitCommand=new Command("Exit",Command.EXIT,0);
    	protected void destroyApp(boolean unconditional)
    			throws MIDletStateChangeException {}
    
    	protected void pauseApp() {	}
    
    	protected void startApp() throws MIDletStateChangeException {
    		t=new Thread(this);
    		t.start();
    		f=new Form("Multi Connections");
    		f.addCommand(infoCommand);
    		f.addCommand(exitCommand);
    		f.setCommandListener(this);
    		Display.getDisplay(this).setCurrent(f);
    	}
    	
    	private String connect(String targetUrl) 
    	{
    		String response="";
    		HttpConnection connection = null;
    		InputStream inputstream = null;
    	    try
    	    {
    	    	connection = (HttpConnection) Connector.open(targetUrl);
    	        //HTTP Request
    	        connection.setRequestMethod(HttpConnection.GET);
    	        // HTTP Response
    	        if (connection.getResponseCode() == HttpConnection.HTTP_OK)
    	        {	          
    	        	inputstream = connection.openInputStream();
    	        	int length = (int) connection.getLength();
    	        	if (length != -1)
    	        	{
    	        		byte incomingData[] = new byte[length];
    	        		inputstream.read(incomingData);
    	        		response = new String(incomingData);
    	        	}
    	        	else  
    	        	{
    	        		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    	        		int ch;
    	        		while ((ch = inputstream.read()) != -1)
    	        		{
    	        			bytestream.write(ch);
    	        		}
    	        		response = new String(bytestream.toByteArray());
    	        		bytestream.close();	            
    	        	}	          
    	        }
    	    }	
    	    catch(IOException error)
    	    {
    	       System.out.println("Caught IOException: " + error.toString());	       
    	    }
    	    finally
    	    {
    	    	if (inputstream!= null)
    	        {
    	          try 
    	          { 
    	            inputstream.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	        if (connection != null)
    	        {
    	          try
    	          {
    	             connection.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	    }
    	    return response;		
    	}
    
    	public void run() {
    		String fetchpage1=connect("http://www.w3.org");
    		f.append("Fetching 1 completed!\n");
    		String fetchpage2=connect("http://www.internet.org");
    		f.append("Fetching 2 completed!");
    	}
    
    	public void commandAction(Command arg0, Displayable arg1) {
    		if(arg0==exitCommand)
    		{
    			notifyDestroyed();
    		}
    		if(arg0==infoCommand)
    		{
    			f.append("App is responsive\n");
    		}
    		
    	}
    }
    thanks & Regards.
    Nilesh

  6. #6
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: J2ME Multithread concept for asyn call .. Download images

    You can check this example:
    http://www.developer.nokia.com/Commu...multithreading
    where multiple instances of a class (which is equivalent to different objects) are using the same method to connect to a web page. You can replace the fetch method of the example with your download method and synchronize the access to your download method, in a similar way as in the connection class of the example.

  7. #7
    Registered User
    Join Date
    Jun 2010
    Location
    India
    Posts
    200

    Re: J2ME Multithread concept for asyn call .. Download images

    hey thanx dude.........

    but still they taken midlet class reference into connection class...& i dont want this .............

    thanks again for help...........

    Quote Originally Posted by skalogir View Post
    You can check this example:
    http://www.developer.nokia.com/Commu...multithreading
    where multiple instances of a class (which is equivalent to different objects) are using the same method to connect to a web page. You can replace the fetch method of the example with your download method and synchronize the access to your download method, in a similar way as in the connection class of the example.
    thanks & Regards.
    Nilesh

  8. #8
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: J2ME Multithread concept for asyn call .. Download images

    You can easily remove the reference to the MIDlet, by statically calling the fetch method. You can also place the fetch method in a separate class if you like. For example you can do this:

    MultipleConnections MIDlet:
    Code:
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    
    public class MultipleConnections extends MIDlet implements CommandListener{
    
    	static Form mainform;
    	Command infoCommand=new Command("Info",Command.OK,1);
    	Command exitCommand=new Command("Exit",Command.EXIT,0);
    	connection con1;
    	connection con2;
    	connection con3;
    	static boolean istaken;
    	
    	protected void destroyApp(boolean unconditional)
    			throws MIDletStateChangeException {}
    
    	protected void pauseApp() {	}
    
    	protected void startApp() throws MIDletStateChangeException {
    		istaken=false;
    		mainform=new Form("Multi Connections");
    		mainform.addCommand(infoCommand);
    		mainform.addCommand(exitCommand);
    		con1=new connection("http://www.w3schools.com/html/default.asp");
    		con2=new connection("http://www.w3schools.com/html/html_fonts.asp");
    		con3=new connection("http://www.w3schools.com/html/html_xhtml.asp");
    		mainform.setCommandListener(this);
    		Display.getDisplay(this).setCurrent(mainform);
    	}
    	public static boolean isTaken()
    	{
    		return istaken;
    	}
    	public Form getForm()
    	{
    		return mainform;
    	}
    	public void commandAction(Command arg0, Displayable arg1) {
    		if(arg0==exitCommand)
    		{
    			notifyDestroyed();
    		}
    		if(arg0==infoCommand)
    		{
    			mainform.append("\nMIDlet is responsive\n");
    		}
    	}
    }
    connection class:
    Code:
    public class connection implements Runnable{
    	static boolean istaken=false;
    	Thread t;
    	String targetUrl;
    	
    	connection(String url)
    	{
    		targetUrl=url;
    		t=new Thread(this);
    		t.start();	
    	}
    
    	public void run() {
    		while(MultipleConnections.isTaken())
    		{
    		
    			try
    			{
    				Thread.sleep(2000);			
    			}
    			catch(Exception e){}
    		}
    		connect.fetch(targetUrl);
    	}
    	
    
    }
    connect class:
    Code:
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    
    
    public class connect {
    	
    	public static void fetch(String targetUrl)
    	{
    		MultipleConnections.istaken=true;
    		MultipleConnections.mainform.append("\nRetrieving page...\n");
    		String response="";
    		String substr="";
    		HttpConnection connection = null;
    		InputStream inputstream = null;
    	    try
    	    {
    	    	connection = (HttpConnection) Connector.open(targetUrl);
    	        //HTTP Request
    	        connection.setRequestMethod(HttpConnection.GET);
    	        // HTTP Response
    	        if (connection.getResponseCode() == HttpConnection.HTTP_OK)
    	        {	          
    	        	inputstream = connection.openInputStream();
    	        	int length = (int) connection.getLength();
    	        	if (length != -1)
    	        	{
    	        		byte incomingData[] = new byte[length];
    	        		inputstream.read(incomingData);
    	        		response = new String(incomingData);
    	        	}
    	        	else  
    	        	{
    	        		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    	        		int ch;
    	        		while ((ch = inputstream.read()) != -1)
    	        		{
    	        			bytestream.write(ch);
    	        		}
    	        		response = new String(bytestream.toByteArray());
    	        		bytestream.close();	            
    	        	}	          
    	        }
    	    }	
    	    catch(IOException error)
    	    {
    	       System.out.println("Caught IOException: " + error.toString());	       
    	    }
    	    finally
    	    {
    	    	if (inputstream!= null)
    	        {
    	          try 
    	          { 
    	            inputstream.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	        if (connection != null)
    	        {
    	          try
    	          {
    	             connection.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	    }
    	    if(response.indexOf("<title>")>=1 && response.indexOf("</title>")>=1)
    	    {
    	    	int start=response.indexOf("<title>");
    	    	int end=response.indexOf("</title>");
    	    	substr=response.substring(start+7,end);
    	    	MultipleConnections.mainform.append("The title of the page is: "+substr);
    	    }
    	    else
    	    {
    	    	MultipleConnections.mainform.append("The title of the page could not be retrieved");
    	    }
    	    MultipleConnections.mainform.append("\nDone!\n\n");
    	    MultipleConnections.istaken=false;
    	}
    }

  9. #9
    Registered User
    Join Date
    Jun 2010
    Location
    India
    Posts
    200

    Re: J2ME Multithread concept for asyn call .. Download images

    thnx dude,,,
    i'' ll try then told u ...
    Quote Originally Posted by skalogir View Post
    You can easily remove the reference to the MIDlet, by statically calling the fetch method. You can also place the fetch method in a separate class if you like. For example you can do this:

    MultipleConnections MIDlet:
    Code:
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    
    public class MultipleConnections extends MIDlet implements CommandListener{
    
    	static Form mainform;
    	Command infoCommand=new Command("Info",Command.OK,1);
    	Command exitCommand=new Command("Exit",Command.EXIT,0);
    	connection con1;
    	connection con2;
    	connection con3;
    	static boolean istaken;
    	
    	protected void destroyApp(boolean unconditional)
    			throws MIDletStateChangeException {}
    
    	protected void pauseApp() {	}
    
    	protected void startApp() throws MIDletStateChangeException {
    		istaken=false;
    		mainform=new Form("Multi Connections");
    		mainform.addCommand(infoCommand);
    		mainform.addCommand(exitCommand);
    		con1=new connection("http://www.w3schools.com/html/default.asp");
    		con2=new connection("http://www.w3schools.com/html/html_fonts.asp");
    		con3=new connection("http://www.w3schools.com/html/html_xhtml.asp");
    		mainform.setCommandListener(this);
    		Display.getDisplay(this).setCurrent(mainform);
    	}
    	public static boolean isTaken()
    	{
    		return istaken;
    	}
    	public Form getForm()
    	{
    		return mainform;
    	}
    	public void commandAction(Command arg0, Displayable arg1) {
    		if(arg0==exitCommand)
    		{
    			notifyDestroyed();
    		}
    		if(arg0==infoCommand)
    		{
    			mainform.append("\nMIDlet is responsive\n");
    		}
    	}
    }
    connection class:
    Code:
    public class connection implements Runnable{
    	static boolean istaken=false;
    	Thread t;
    	String targetUrl;
    	
    	connection(String url)
    	{
    		targetUrl=url;
    		t=new Thread(this);
    		t.start();	
    	}
    
    	public void run() {
    		while(MultipleConnections.isTaken())
    		{
    		
    			try
    			{
    				Thread.sleep(2000);			
    			}
    			catch(Exception e){}
    		}
    		connect.fetch(targetUrl);
    	}
    	
    
    }
    connect class:
    Code:
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    
    
    public class connect {
    	
    	public static void fetch(String targetUrl)
    	{
    		MultipleConnections.istaken=true;
    		MultipleConnections.mainform.append("\nRetrieving page...\n");
    		String response="";
    		String substr="";
    		HttpConnection connection = null;
    		InputStream inputstream = null;
    	    try
    	    {
    	    	connection = (HttpConnection) Connector.open(targetUrl);
    	        //HTTP Request
    	        connection.setRequestMethod(HttpConnection.GET);
    	        // HTTP Response
    	        if (connection.getResponseCode() == HttpConnection.HTTP_OK)
    	        {	          
    	        	inputstream = connection.openInputStream();
    	        	int length = (int) connection.getLength();
    	        	if (length != -1)
    	        	{
    	        		byte incomingData[] = new byte[length];
    	        		inputstream.read(incomingData);
    	        		response = new String(incomingData);
    	        	}
    	        	else  
    	        	{
    	        		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    	        		int ch;
    	        		while ((ch = inputstream.read()) != -1)
    	        		{
    	        			bytestream.write(ch);
    	        		}
    	        		response = new String(bytestream.toByteArray());
    	        		bytestream.close();	            
    	        	}	          
    	        }
    	    }	
    	    catch(IOException error)
    	    {
    	       System.out.println("Caught IOException: " + error.toString());	       
    	    }
    	    finally
    	    {
    	    	if (inputstream!= null)
    	        {
    	          try 
    	          { 
    	            inputstream.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	        if (connection != null)
    	        {
    	          try
    	          {
    	             connection.close();
    	          }
    	          catch( Exception error)
    	          {
    	             /*log error*/
    	          }
    	        }
    	    }
    	    if(response.indexOf("<title>")>=1 && response.indexOf("</title>")>=1)
    	    {
    	    	int start=response.indexOf("<title>");
    	    	int end=response.indexOf("</title>");
    	    	substr=response.substring(start+7,end);
    	    	MultipleConnections.mainform.append("The title of the page is: "+substr);
    	    }
    	    else
    	    {
    	    	MultipleConnections.mainform.append("The title of the page could not be retrieved");
    	    }
    	    MultipleConnections.mainform.append("\nDone!\n\n");
    	    MultipleConnections.istaken=false;
    	}
    }
    thanks & Regards.
    Nilesh

Similar Threads

  1. Replies: 1
    Last Post: 2004-02-05, 08:06
  2. help with j2me games concept
    By angjiyong in forum Mobile Java General
    Replies: 0
    Last Post: 2004-02-02, 19:53
  3. J2ME 7650 grpahics, A concept question
    By shahzad73 in forum Mobile Java General
    Replies: 0
    Last Post: 2002-12-24, 06:20
  4. Replies: 2
    Last Post: 2002-12-03, 03:58

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •