11-17-2012 02:11 AM
I am attempting to get images from an online source, but they don't seem to display.
Here is my code:
String stringimgpath = new String("http://sample.com/image.jpg");
StreamConnection getimg = (StreamConnection)Connector.open(stringimgpath);
InputStream httpInput = getimg.openInputStream();
InputStream inp = httpInput;
byte b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
Bitmap bitmp = hai.getBitmap();
BitmapField bitmapField = new BitmapField(bitmp);
11-17-2012 08:25 AM - edited 11-17-2012 08:26 AM
There are possibly a few issues in the code you are using, it is difficult to say exactly what is causing the failure to display when you don't tell us what happens. For example, I am betting this throws an exception somewhere - but which line?
This sort of thing is easy for you - just step through it with the debugger. And the more you tell us the more likely we are to be able to help you.
Anyway three things to immediately note.
1) You can not perform blocking operations on the Event Thread. This code is doing a blocking operation (getting data) and updating the UI (add the bitmapField). You will need to separate these two. have a look at this:
2) I think you would better treating this request as an httpConnection, since that is actually what it is. Wit the http connection, you will get a response code and you should really check out the response code before you attempt to process anything.
3) I suspect you are not familiar with the myriad of different connection options, so please review this:
But if you are writing for OS 5.0 and above, then i recommend you use ConnectionFactory and let it sort things out for you.
If you want a general example of something that does it http connection off the Event Thread, look at httpDemo sample. Search the forum for more information on ConnectionFactory. And while you are there, there is some sample code on the forum designed specifically to download images (at least I remember seeing some) - you might find this code useful reference so have a look for it.