Question

I am new to BlackBerry development. But good about android.

I want to load Images coming from the server in ListField.

I have implement like below code but not getting success:

   package mypackage;


public class TempScreen extends MainScreen implements ListFieldCallback{
    Bitmap[] images=null;
    private ListField mylist;
    private static Bitmap _bitmap;
    private ImageDownloader downloader;
    int size = 0;
    String[] urls={
            "http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
            "http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
            "http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
            "http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg"};
    public TempScreen()
    {


        images=new Bitmap[urls.length];
        size = urls.length;
        mylist = new ListField();
        mylist.setCallback(this);
        mylist.setSize(4);
        mylist.setRowHeight(getFont().getHeight() * 3);
        add(mylist);
        Thread downloader=new Thread(new ImageDownloader());
        downloader.start();

    }


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

        if(images[index]==null)
         {
             //Load placeholder image
            _bitmap = Bitmap.getBitmapResource("close_btn.png");// load some bitmap
            // of your choice
            // here
         }
         else
             //Load Bitmap
            _bitmap = images[index]; 

        graphics.drawText("row details", 100, y + 30);
        //graphics.drawBitmap(0, y, _bitmap.getWidth(), _bitmap.getHeight(),_bitmap, 0, 0);
        mylist.invalidate(index);
    }

    public class ImageDownloader implements Runnable
    {
        public void run()
        { 
            for(int i=0; i<size;i++)
            { 
                 if(images[i]==null) 
                 { 
                      images[i]=connectServerForImage(urls[i].toString());//replace downloadImage method to whatever method       you have to download the bitmap from url 
                      UiApplication.getUiApplication().invokeLater(new Runnable(){
                          public void run()
                          {
                              mylist.invalidate();
                          }
                      });
                  }
             }
        }
    }
    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;
    }
    public static Bitmap connectServerForImage(String url) {
        HttpConnection httpConnection = null;
        DataOutputStream httpDataOutput = null;
        InputStream httpInput = null;
        int rc;
        Bitmap bitmp = null;
        try {
            // httpConnection = (HttpConnection)
            // Connector.open(url+";interface=wifi");
            httpConnection = (HttpConnection) Connector.open(url);
            rc = httpConnection.getResponseCode();
            // System.out.println("===============================");
            Dialog.alert("beore if condition");
            if (rc == HttpConnection.HTTP_OK) {

                System.out.println(" ============= IN FUNCTION. . . . .");
                httpInput = httpConnection.openInputStream();
                InputStream inp = httpInput;
                byte[] b = IOUtilities.streamToBytes(inp);
                EncodedImage hai = EncodedImage.createEncodedImage(b, 0,
                        b.length);
                bitmp = hai.getBitmap();
            } else {
                throw new IOException("HTTP response code: " + rc);
            }
        } catch (Exception ex) {
            System.out.println("URL Bitmap Error........" + ex.getMessage());
        } finally {
            try {
                if (httpInput != null)
                    httpInput.close();
                if (httpDataOutput != null)
                    httpDataOutput.close();
                if (httpConnection != null)
                    httpConnection.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bitmp;
    }
}

Dont know where i am wrong. Please can any budy help me for the same.

Was it helpful?

Solution 2

You can try using this link : http://www.coderholic.com/blackberry-webbitmapfield/

You have to create a separate class named as WebBitmapField as suggested in above link.

How to use that class in your list field image objects:

  • For every image url create WebBitmapField object
  • photoList_vector is the vector through which populate elements in list field

    WebBitmapField web = new WebBitmapField("http://www.image1.png"); 
    
    photoList_vector.addElement(web);
    
    web = new WebBitmapField("http://www.image2.png"); 
    
    photoList_vector.addElement(web);
    

Now use this vector to work on your list field......

In the above lines we try to ensure that when we simultaneously send multiple requests to get the images then each image corresponds to a particular WebBitmapField Object.

Each object is then added to vector so that it can be added to the list field.

Each url send is tied to an object of WebBitmapField.

So though request is send in a separate thread it gets tied to its associated object only

Hope it helps :)

OTHER TIPS

Several problems with your code:

  • The BitmapLazyLoader class looks like a consumer. It holds a Thread reference. This alone is very confusing, since Runnables are intended to be passed to a Thread constructor, but Runnables should not know about the thread for the sake of encapsulation. Letting this apart, this class attempts to spawn a thread only once, but as you are creating an instance of Runnable each time a row is drawn, you'll end up spawning a considerable number of threads. This will probably end in a TooManyThreadsException being thrown as in BlackBerry the max number of threads is limited to 16 per app. Even if you don reach the limit, performance will degrade as BlackBerries, which sport a single core CPU, you shouldn't have more than 2-3 threads running at the same time. EVEN if you could spawn infinite threads, in BlackBerry you can only have X connections opened at the same time (I think X is 5 for the whole OS, not sure about this). So first of all modify the code to ensure only a single worker thread is downloading images. (and if possible, extract the thread instantiation and launch out of the Runnable class).
  • When the bitmap is downloaded, you are not doing anything with it. Look at the ImageDownloadCompleted method, it is empty. (BTW, the convention for methods is to start with lowercase) So you should store the bitmap somewhere and call invalidate on your list, which in turn will paint the stored bitmaps.

Hope it helps.

I have worked on this problem, earlier, and I am posting my technique here, though its not ideal solution, as it was coupled very much with Screen class, but still might be helpful.

First in your screen class have one array for bitmaps having size equal to list field items.

public class TempScreen extends MainScreen{
    Bitmap[] images=null;
    String[] urls={"image1_url", "image2_url".....};
    public TempScreen()
    {

        images=new Bitmap[urls.length];

    }

now in drawListRow method of ListFieldCallBack, check for the following:

 public void drawListRow(ListField list, Graphics g, int index, int y, int width){
     if(bitmap[index]==null)
     {
         //Load placeholder image
     }
     else
         //Load Bitmap    
 }

Now create a thread class to download the images:

public class ImageDownloader implements Runnable
{
    public void run()
    { 
        for(int i=0; i<size;i++)
        { 
             if(images[i]==null) 
             { 
                  images[i]=downloadImage(url[i]);//replace downloadImage method to whatever method       you have to download the bitmap from url 
                  UiApplication.getUiApplication().invokeLater(new Runnable(){
                      public void run()
                      {
                          list.invalidate()
                      }
                  });
              }
         }
    }
}

Now in constructor of the screen class, after setting callback to listfield, start thread:

Thread downloader=new Thread(new ImageDownloader());
downloader.start();

Edit: Change TempScreen constructor to following:

public TempScreen()
    {

        images=new Bitmap[urls.length];
        size = urls.length;
        mylist = new ListField();
        mylist.setCallback(this);
        mylist.setSize(4);
        mylist.setRowHeight(getFont().getHeight() * 3);
        add(mylist);
        Thread downloader=new Thread(new ImageDownloader());
        downloader.start();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top