Bitmap Image not displaying from a URL link Blackberry
Asked Answered
A

2

0

For some reason my blackberry application crashes whenever i try to display a bitmap image from a URL using the internet.

I found the downloadImage() function very easy to understand and to follow compared to others on stackoverflow. The others didnt have any examples on how to implement their function. I have have tested the function downloadImage many times and all failed.

Please give explanation with code example. Thanks.

Anyway, The compiler stops at this point here:

g.drawBitmap(10, y + 6, 50, 50, imageBmp, 0, 0);

Here is the entire code:

package parsepack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class xmlparsing extends UiApplication implements ListFieldCallback, FieldChangeListener 
{

    public static void main(String[] args) throws IOException
    {
    xmlparsing app = new xmlparsing();
    app.enterEventDispatcher();
    }


public long mycolor ;
Connection _connectionthread;     
private static ListField _list;
private static Vector listElements = new Vector();
private static Vector listPrice = new Vector();
private static Vector listAbstract = new Vector();
private static Vector listIcon = new Vector();
private Vector listInfoVector = new Vector();
public MainScreen screen = new MainScreen();
Bitmap imageBmp = null;
VerticalFieldManager mainManager;
VerticalFieldManager subManager;
UiApplication ui = UiApplication.getUiApplication(); 


public  xmlparsing() throws IOException 
{ 
    super();
    pushScreen(screen);

    final Bitmap backgroundBitmap = Bitmap.getBitmapResource("blackbackground.png");

     mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
        {

         public void paint(Graphics graphics)
          {
            graphics.drawBitmap(0, 0, Display.getWidth(),Display.getHeight(),backgroundBitmap, 0, 0);

            super.paint(graphics);
          }

        };

        subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
        {
            protected void sublayout( int maxWidth, int maxHeight )
            {
                int displayWidth = Display.getWidth();
                int displayHeight = Display.getHeight();

                super.sublayout( displayWidth, displayHeight);
                setExtent( displayWidth, displayHeight);
            }
        };        


    screen.add(mainManager);





    _list = new ListField()
    {
        public void paint(Graphics graphics)
        {
            graphics.setColor((int) mycolor);
            super.paint(graphics);
        }
        protected boolean navigationClick(int status, int time)
        {
            try
            {
                //navigate here to another screen
                ui.pushScreen(new ResultScreen());
            }
            catch(Exception e)
            {
                System.out.println("Exception:-  : navigationClick() "+e.toString());
            }
            return true;
        }
    }; 
    mycolor = 0x00FFFFFF;
        _list.invalidate();
        _list.setEmptyString("* Feeds Not Available *", DrawStyle.HCENTER);
    _list.setRowHeight(70);
    _list.setCallback(this);
    mainManager.add(subManager);    
   listElements.removeAllElements();
   listPrice.removeAllElements();
   listAbstract.removeAllElements();
   listIcon.removeAllElements();
   _connectionthread = new Connection(); 
   _connectionthread.start();
 }


private class Connection extends Thread
{ 
    public Connection()
    { 
       super(); 
    } 

    public void run() {  
        Document doc;  
        StreamConnection conn = null; 
        InputStream is = null;  
        try {           

            conn = (StreamConnection) Connector.open("http://imforchange.org/international-movement-for-change/testing/data.xml"+";deviceside=true");           

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();  
            docBuilderFactory.setIgnoringElementContentWhitespace(true);
            docBuilderFactory.setCoalescing(true);
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();    
            docBuilder.isValidating();      
            is = conn.openInputStream();    
            doc = docBuilder.parse(is);     
            doc.getDocumentElement().normalize();   
            NodeList list1 = doc.getElementsByTagName("eventName"); 
                for (int i = 0; i < list1.getLength(); i++) {    
                Node textNode = list1.item(i).getFirstChild();  
                listElements.addElement(textNode.getNodeValue());

                } 
                NodeList list2 = doc.getElementsByTagName("eventPrice"); 
                for (int i = 0; i < list2.getLength(); i++) {    
                Node textNode = list2.item(i).getFirstChild();  
                listPrice.addElement(textNode.getNodeValue());

                } 

                NodeList list3 = doc.getElementsByTagName("eventAbstract"); 
                for (int i = 0; i < list3.getLength(); i++) {    
                Node textNode = list3.item(i).getFirstChild();  
                listAbstract.addElement(textNode.getNodeValue());

                }

                NodeList list4 = doc.getElementsByTagName("eventIcon"); 
                for (int i = 0; i < list4.getLength(); i++) {    
                Node textNode = list4.item(i).getFirstChild();  
                listIcon.addElement(textNode.getNodeValue());

                }



                } catch (Exception e) {   
                    System.out.println(e.toString());                     
                    } finally {   
                        if (is != null) {  
                        try { is.close(); 
                        } catch (IOException ignored) {}   
                        }        if (conn != null) {  
                            try { conn.close(); } 
                            catch (IOException ignored) {} 
                            }    } UiApplication.getUiApplication().invokeLater(new Runnable() { 
                                public void run() {         
                                _list.setSize(listElements.size()); 
                                subManager.add(_list);
                                screen.invalidate();
                                }   
                                });
                            }





}




public void drawListRow(ListField list, Graphics g, int index, int y, int w) 
{  


    String text = (String)listElements.elementAt(index);
    String price = (String)listPrice.elementAt(index);
    String textAbstract = (String)listAbstract.elementAt(index);
    int yPos = 0+y;
    g.drawLine(0, yPos, w, yPos);
    g.drawText(text, 5, 15+y, 0, w);
    g.drawText("$"+price, 5, 15+y, DrawStyle.RIGHT, w-7);
    g.drawText(textAbstract, 5, 40+y, 0, w);



    // image to display
    String imageUrl = (String)listIcon.elementAt(index);
    imageBmp = downloadImage(imageUrl);
    g.drawBitmap(10, y + 6, 50, 50, imageBmp, 0, 0);
}



public Object get(ListField list, int index) 
{
    return listElements.elementAt(index); 
} 
public int indexOfList(ListField list, String prefix, int string) 
{ 
    return listElements.indexOf(prefix, string); 
} 
public int getPreferredWidth(ListField list) 
{ 
 return Display.getWidth(); 
}

/*Regarding the warning about insert(), that's just because you're not using it anywhere. 
 * It look like you've added that method to allow code outside the xmlparsing class to 
 * be able to insert items into the list. Maybe that's what you want, but you just 
 * haven't yet written the other code to use that method. I see you having at least a few choices:
 */
public void insert(String toInsert, int index) {
    listElements.addElement(toInsert);
    }

public void fieldChanged(Field field, int context) {


}


public static Bitmap downloadImage(String url)
{
InputStream iStream = null;
EncodedImage bitmap;
    HttpConnection httpConnection = null;

        try
        {
                    httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);

            httpConnection.setRequestMethod(HttpConnection.GET);
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpConnection.HTTP_OK) {


                iStream = httpConnection.openInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                byte[] buffer = new byte[256];
                int len = 0, imageSize = 0;

                while (-1 != (len = iStream.read(buffer))) {
                    byteArrayOutputStream.write(buffer);
                    imageSize += len;
                }

                byteArrayOutputStream.flush();
                byte[] imageData = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
                bitmap = EncodedImage.createEncodedImage(imageData, 0, imageSize);                                      
                Bitmap bmp = bitmap.getBitmap();

return bmp;
            }
            }
            catch (Exception e)
            {                      
            }
return null;                  
}




}
Arbil answered 20/10, 2012 at 7:0 Comment(1)
I saw your Code,In that you had Parsed an xml file.and grabbed the value of image and you want to display the image on the Blackberry screen.But you are saying that you are unable to display the image. Similar to your requirement check this article .There you will find an answer to your Question.Artemisa
A
1

If you want to Display an Image on BlackBerry Screen from a WebURL. First you need to get a BitMap refrence.

You can Check the below Code:

The Code will take input as WebURL and It will return a Bitmap reference.

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;

        public class GetImage {
        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);
        rc = httpConnection.getResponseCode();
        if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
        }
        httpInput = httpConnection.openInputStream();
        InputStream inp = httpInput;
        byte[] b = IOUtilities.streamToBytes(inp);
        EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
        return hai.getBitmap();
        } 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;
        }
          }

And Finally,If you want to Display the Image on BlackBerry Screen, use the below method

g.drawBitmap(xpos, ypos, w, h, image, 0, 0);//pass the Bitmap reference Here
Artemisa answered 20/10, 2012 at 9:34 Comment(0)
C
1

I see your method: downloadImage(String url). Its a lengthy code. No need that much;

Try this method:

public static Bitmap getImage(String url)
{
    Bitmap image;
    HttpConnection connection=null;
    InputStream is=null;
    try
    {
        connection=(HttpConnection)Connector.open(Utility.escapeHTML(url));
        int response=connection.getResponseCode();
        if(response==HttpConnection.HTTP_OK)
        {   
            is=connection.openInputStream();
            byte[] data=IOUtilities.streamToBytes(is);
            connection.close();
            image=Bitmap.createBitmapFromBytes(data,0,data.length,1);
        }
        else
        {
                image=ResourceList.dummyBit;//noimage.png               
        }
    }
    catch (Exception e) 
    {
        image=ResourceList.dummyBit;//noimage.png               
    }
    finally
    {
        try 
        {
            if (is != null)
                is.close();
            if (connection != null)
                connection.close();
        }
        catch (Exception e) {}
    }
    return image;
}

try this and let me know.

the escapeHTML(String str) method is below:

public static String escapeHTML(String s)
{
    StringBuffer sb = new StringBuffer();
    int n = s.length();
       for (int i = 0; i < n; i++) {
          char c = s.charAt(i);
          switch (c) {
             case ' ': sb.append("%20"); break;
             default:  sb.append(c); break;
        }
    }
    return sb.toString();
}
Cowboy answered 20/10, 2012 at 8:2 Comment(2)
thanks alot for your help. I tried it and i was getting a problem with this line of code connection=(HttpConnection)Connector.open(Utility.escapeHTML(url)); The Utility was not recognized or was missing a class.Arbil
Oh, I am not provided you that method. I edited please look it once. I put that because if the URL has any SPACES then it should not work. For this we have to replace SPACES with "%20".Cowboy
A
1

If you want to Display an Image on BlackBerry Screen from a WebURL. First you need to get a BitMap refrence.

You can Check the below Code:

The Code will take input as WebURL and It will return a Bitmap reference.

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;

        public class GetImage {
        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);
        rc = httpConnection.getResponseCode();
        if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
        }
        httpInput = httpConnection.openInputStream();
        InputStream inp = httpInput;
        byte[] b = IOUtilities.streamToBytes(inp);
        EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
        return hai.getBitmap();
        } 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;
        }
          }

And Finally,If you want to Display the Image on BlackBerry Screen, use the below method

g.drawBitmap(xpos, ypos, w, h, image, 0, 0);//pass the Bitmap reference Here
Artemisa answered 20/10, 2012 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.