Skip to content

Instantly share code, notes, and snippets.

@anta40
Created May 30, 2015 03:23
Show Gist options
  • Save anta40/93f1aea80d4de09ca77a to your computer and use it in GitHub Desktop.
Save anta40/93f1aea80d4de09ca77a to your computer and use it in GitHub Desktop.
Load bitmap from a URL on BlackBerry (pre OS 10)
public static Bitmap loadBitmapFromURL(String url){
TransportManager connManager = TransportManager.getInstance();
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) connManager.getConnection(url, Connector.READ_WRITE, true);
httpConnection.setRequestMethod(HttpConnection.GET);
httpConnection.setRequestProperty("Connection", "Keep-Alive");
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
byte buffer[] = new byte[10000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int bytesRead = httpInput.read(buffer); bytesRead > 0; bytesRead = httpInput.read(buffer)){
baos.write(buffer, 0, bytesRead);
}
baos.close();
byte[] ddd = baos.toByteArray();
EncodedImage ei = JPEGEncodedImage.createEncodedImage(ddd, 0, ddd.length);
return ei.getBitmap();
} catch (Exception ex) {
bitmp = Bitmap.getBitmapResource("img/blank.png");
}
finally {
try {
if (httpInput != null) httpInput.close();
if (httpDataOutput != null) httpDataOutput.close();
if (httpConnection != null) httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment