Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Highlighted
Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd
Accepted Solution

show images in List filed

[ Edited ]

hi, i have created a list filed which contains a Picture and some data in one row 
the picture and data i am getting from Json.My code is working but after getting the list my UI is hanging,
There are Two steps 
1) parse the data and image url from json
2) and show in lIst field
i'll post my code and screen shot of List below  

public final class MyScreen extends MainScreen implements ListFieldCallback
{
	HttpConnection httpConn;
	int responseCode;
	private static ListField _list;
	private static Vector listElements = new Vector();
	private static Vector elements = new Vector();
	private static Vector contentelements = new Vector();
	private static Vector datelements = new Vector();
	private static Vector Imageselements = new Vector();
	
	LabelField label;
	String imagename;
	
	Bitmap bit ;
    BitmapField pic;
	
    public MyScreen()
    {        
        // Set the displayed title of the screen  
        //setTitle("MyTitle");
        
        _list = new ListField();
        
        _list.invalidate();
		_list.setEmptyString("please wait..", DrawStyle.HCENTER);
		_list.setRowHeight(100);
		_list.setCallback(this);
		add(_list);
        
        try {
            String httpURL = "URL";  
            
            httpConn = (HttpConnection) Connector.open(httpURL);
            httpConn.setRequestMethod(HttpConnection.GET);
            
            responseCode = httpConn.getResponseCode(); 
			if (responseCode != HttpConnection.HTTP_OK) 
			{ 
				throw new IOException("HTTP response code: "+ responseCode); 
				
			}else{
				
				System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
           
            DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
           
            byte[] request_body = httpURL.getBytes();
            for (int i = 0; i < request_body.length; i++) {
            
            	_outStream.writeByte(request_body[i]);
            }
            
            DataInputStream _inputStream = new DataInputStream(
            httpConn.openInputStream());
            
            StringBuffer _responseMessage = new StringBuffer();
            int ch;
            while ((ch = _inputStream.read()) != -1) {
            
            	_responseMessage.append((char) ch);
            }
            
            String res = (_responseMessage.toString());
            String responce = res.trim();
            System.out.println("\nresponce"+responce);
            

            JSONArray jsnarry = new JSONArray(responce);
			
			System.out.println("\n--length----- "+jsnarry.length());
			
			for (int i = 0; i < jsnarry.length(); i++){
				
				JSONArray inerarray = jsnarry.getJSONArray(i);
				System.out.println("\n-innerarray-length----- "+inerarray.length());
				
				//for (int i1 = 0; i1 < inerarray.length(); i1++) {
				    //System.out.println("\n-inerarray-values----- "+inerarray.getString(i1));
				    String ID = inerarray.getString(0);
				    String TITTLE = inerarray.getString(1);
				    String CONTENT = inerarray.getString(2);
				    String DATE = inerarray.getString(3);
				    String IMAGE = inerarray.getString(4);
				    String six = inerarray.getString(5);
				    
				    System.out.println("................................................");
				    System.out.println("ID= "+ID);
				    System.out.println("TITTLE= "+TITTLE);
				    System.out.println("CONTENT= "+CONTENT);
				    System.out.println("DATE= "+DATE);
				    System.out.println("IMAGE= "+IMAGE);
				    imagename = "image URL";
				    System.out.println("imagename= "+imagename);
				    //System.out.println("six "+six);
				    System.out.println("....................................................=");
				   // String jsonresponse = ""+inerarray.getString(i1);
				    //label = new LabelField(jsonresponse,LabelField.FOCUSABLE);
			        //add(label);
				//}
				    elements.addElement(TITTLE);
				    contentelements.addElement(CONTENT);
				    datelements.addElement(DATE);
				    Imageselements.addElement(imagename);
			}

			
			UiApplication.getUiApplication().invokeLater(new Runnable() { 
				
				public void run() { 
			
					try {
						_list.setSize(elements.size());
						_list.setSize(contentelements.size());
						_list.setSize(datelements.size());
						_list.setSize(Imageselements.size());
						//invalidate();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.out.println("error _list.setSize"+e.toString());
					}
			
				} 
			
			});
			}

        } catch (Exception e) {
            // TODO Auto-generated catch block
        	System.out.println("\nresponce"+e.toString());
        }
    }
    
    public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w) {

        try {
			graphics.setGlobalAlpha(255);
			final int margin =5;
			
			String tittle = (String)elements.elementAt(index);
			String content = (String)contentelements.elementAt(index);
			String date = (String)datelements.elementAt(index);
			String imagesurl = (String)Imageselements.elementAt(index);
			
			UrlToImage img = new UrlToImage( imagesurl);
		   
			bit =img.getbitmap();
			
			graphics.drawText(tittle.trim(), 3*margin+bit.getWidth(),  y+margin);
			
			graphics.drawText(content.trim(), 3*margin+bit.getWidth(), y+ margin+30);
			
			graphics.drawText(date.trim(), 3*margin+bit.getWidth(),    y+ margin+60);
			
		    graphics.drawBitmap(2, y+margin+5, bit.getWidth(), bit.getHeight(), bit, 0, 0);
		
        
        } catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("error drawListRow"+e.toString());
		}

    }
    
   
    public Object get(ListField listField, int index) {
    	// TODO Auto-generated method stub
    	return null;
    }

    public int getPreferredWidth(ListField listField) {
    	// TODO Auto-generated method stub
    	return 0;
    }

    public int indexOfList(ListField listField, String prefix, int start) {
    	// TODO Auto-generated method stub
    	return 0;
    }

 UrlToImage.JAVA

public class UrlToImage {

	public static Bitmap _bmap;

	UrlToImage(final String url){
		HttpConnection connection = null; 
		InputStream inputStream = null; 
		EncodedImage bitmap;
		byte[] dataArray = null;

		try { 

			connection = (HttpConnection) Connector.open(url+ getConnectionString(), Connector.READ, true); 
			inputStream = connection.openInputStream(); 
			byte[] responseData = new byte[10000]; 

			int length = 0; 

			StringBuffer rawResponse = new StringBuffer(); 
			while (-1 != (length = inputStream.read(responseData))) 
			{ 
				rawResponse.append(new String(responseData, 0, length)); 
			} 
			int responseCode = connection.getResponseCode(); 
			if (responseCode != HttpConnection.HTTP_OK) 
			{ 
				throw new IOException("HTTP response code: "+ responseCode); 
			}else{
				System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
			}

			final String result = rawResponse.toString(); 
			dataArray = result.getBytes(); 
			System.out.println("\ndataArray.length = "+dataArray.length);
			System.out.println("\ndataArray.length = "+dataArray[0]);
			System.out.println("\ndataArray.length = "+dataArray[1]);
			System.out.println("\ndataArray.length = "+dataArray[2]);
			System.out.println("\ndataArray.length = "+dataArray[3]);

		} catch (final Exception ex) { 
			
		}finally { 

			try { 

				inputStream.close(); 
				inputStream = null; 
				connection.close(); 
				connection = null; 
			} 
			catch(Exception e){
				
			} 
		} 

		bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
		// this will scale your image acc. to your height and width of bitmapfield

		int multH;
		int multW;
		int currHeight = bitmap.getHeight();
		int currWidth = bitmap.getWidth();
		multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(80));//height
		multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(80));//width
		bitmap = bitmap.scaleImage32(multW,multH);

		_bmap=bitmap.getBitmap();

	}
public Bitmap getbitmap()
{

	return _bmap;

}
}

images and Text is showing but UI hangs
 

 

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: show images in List filed

You need to change your code so that you are not running networking code on the Event Thread.  Here are some KB articles that discuss the Event Thread and implications:

 

http://supportforums.blackberry.com/t5/Java-Development/What-is-the-Event-Thread/ta-p/446865

http://supportforums.blackberry.com/t5/Java-Development/Update-a-screen-on-the-Main-Event-Thread/ta-...

http://supportforums.blackberry.com/t5/Java-Development/Blocking-operation-not-permitted-on-event-di...

 

You will want to stall your UI while you download the initial List (you do not need to do this for the images - see later).  To stall your UI, look for the many other Threads on this forum that have discussed it.  "Please wait screen" or "loading screen" being good terms to search for.

 

You need to get off the Event Thread for both the original download when you populate the screen, and the download of the images for each ListField.  But you can put a placeholder image in your ListField and replace if when you get the real image downloaded.  This is called lazy loading. 

 

You will find this is a useful reference for lazy loading of the images in your ListField:

 

http://stackoverflow.com/questions/19331454/custom-list-with-lazy-loading

 

Aside: Can I recommend again you use the facilities provided by an Object language, at least in some small way, and create an Object for your NewsItems. 

Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd

Re: show images in List filed

i have change my code and now i am running my Json parsing code in background

 public MyScreen()
    {        
        // Set the displayed title of the screen  
        //setTitle("MyTitle");
        
        _list = new ListField();
        
        _list.invalidate();
		_list.setEmptyString("please wait..", DrawStyle.HCENTER);
		_list.setRowHeight(100);
		_list.setCallback(this);
		add(_list);
		
		connectionthread = new Connection();
		connectionthread.start();
        
    }

i have done json parsing in 

connectionthread


and my json parsing is running fine but in my json contains 4,or 5 url of image or more than that
this code is giving me the image from url but how should i use it with in my drawListRow() method or should i store them in bitmap array or something else ?
i have posted my UrlToImage.java in my first post 


 

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: show images in List filed

"how should i use it with in my drawListRow()"

 

I thought I had answered this question in my previous post.

 

Put a placeholder image in the ListField and have additional background processing running to download the images.  When they are downloaded, update the associated ListField row.  This is exactly what the code I linked to does.  it is not trivial to do but gives, for me anyway, the best user experience.

Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd

Re: show images in List filed

[ Edited ]

hi, i have place a place holder img as you said and i have started background thread which download the image and show in list filed, i'll post my code 
but I am getting too many thread exception 

public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w) {

        try {
        	graphics.setGlobalAlpha(255);
			final int margin =5;
			
			String tittle = (String)elements.elementAt(index);
			String content = (String)contentelements.elementAt(index);
			String date = (String)datelements.elementAt(index);
			String imagesurl = (String)Imageselements.elementAt(index);
			
			UrlToImage img = new UrlToImage( imagesurl);
		   
			bit =img.getbitmap();
			
			graphics.drawText(tittle.trim(), 3*margin+bit.getWidth(),  y+margin);
			
			graphics.drawText(content.trim(), 3*margin+bit.getWidth(), y+ margin+30);
			
			graphics.drawText(date.trim(), 3*margin+bit.getWidth(),    y+ margin+60);
			
		    graphics.drawBitmap(2, y+margin+5, bit.getWidth(), bit.getHeight(), bit, 0, 0);
		
        
        } catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("error drawListRow"+e.toString());
		}

    }

 imagesurl contains the image URL and pass to UrlToImage.java which download the image in thread 

 

public class UrlToImage {

	public static Bitmap _bmap;

	UrlToImage(final String url){
		
		
		Thread downloadimg = new Thread(){
			
			public void run(){
				
				try{
					HttpConnection connection = null; 
					InputStream inputStream = null; 
					EncodedImage bitmap;
					byte[] dataArray = null;

					try { 

						connection = (HttpConnection) Connector.open(url+ getConnectionString(), Connector.READ, true); 
						inputStream = connection.openInputStream(); 
						byte[] responseData = new byte[10000]; 

						int length = 0; 

						StringBuffer rawResponse = new StringBuffer(); 
						while (-1 != (length = inputStream.read(responseData))) 
						{ 
							rawResponse.append(new String(responseData, 0, length)); 
						} 
						int responseCode = connection.getResponseCode(); 
						if (responseCode != HttpConnection.HTTP_OK) 
						{ 
							throw new IOException("HTTP response code: "+ responseCode); 
						}else{
							System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
						}

						final String result = rawResponse.toString(); 
						dataArray = result.getBytes(); 
						/*System.out.println("\ndataArray.length = "+dataArray.length);
						System.out.println("\ndataArray.length = "+dataArray[0]);
						System.out.println("\ndataArray.length = "+dataArray[1]);
						System.out.println("\ndataArray.length = "+dataArray[2]);
						System.out.println("\ndataArray.length = "+dataArray[3]);*/

					} catch (final Exception ex) { 
						
					}finally { 

						try { 

							inputStream.close(); 
							inputStream = null; 
							connection.close(); 
							connection = null; 
						} 
						catch(Exception e){
							
						} 
					} 

					bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
					// this will scale your image acc. to your height and width of bitmapfield

					int multH;
					int multW;
					int currHeight = bitmap.getHeight();
					int currWidth = bitmap.getWidth();
					multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(80));//height
					multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(80));//width
					bitmap = bitmap.scaleImage32(multW,multH);

					_bmap=bitmap.getBitmap();

					
				}catch(Exception e){
					
					System.out.println(e.toString());
				}
				
			}
		};downloadimg.start();
		
	
		
	}
 
	
public Bitmap getbitmap()
{

	return _bmap;

}


}

 

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: show images in List filed

If you review the stackoverflow link I posted previously, you will see in there mention of a need for a Thread pool - in other words using a pool of Threads rather than one Thread per download.  This is what you need to do, as starting an individual Thread for every download is starting too many Threads. 

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: show images in List filed

Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd

Re: show images in List filed

[ Edited ]

got the solution , but i got the followig in my console when i download and resize the image
 "FASTJPEG: Progressive decoding is not supported".  what does it mean ?

Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd

Re: show images in List filed

please tell me why i'm getting
"FASTJPEG: Progressive decoding is not supported" ?
Super Contributor
Posts: 425
Registered: ‎01-02-2013
My Device: BOLD 9900
My Carrier: sdvsdvsd

Re: show images in List filed

any solution for my above issue ?