Download image in blackberry and display - blackberry

I use following code to download jpg image and display in blackberry curve 8900 simulator. When I am trying to load my code, it strucks completely and stop responding. Please some one help me.
public DisplayBusinessDetail(String city,Business business)
{
AbsoluteFieldManager absoluteFieldManager = new AbsoluteFieldManager();
absoluteFieldManager.add(new BitmapField(connectServerForImage("http://www.mobileapples.com/Assets/Content/Wallpapers/Blackberry.jpg")),0,0);
add(absoluteFieldManager);
}
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;
}
Thank you in advance

You need to move the socket code off of the main UI event thread. Your code does the download on the UI thread, meaning no UI responsiveness while downloading the bytes.

Related

Blackberry convert Base64 data to byte array showing IOException

I have developed the below code to convert base64 string data to byte array but it's showing IOException
public static EncodedImage getProfileByteArray(String profilePic){
byte[] data=profilePic.getBytes();
byte[] base64Data;
Bitmap bitmap=null;
EncodedImage fullImage=null;
try {
base64Data = Base64InputStream.decode(data, 0, data.length);
fullImage = EncodedImage.createEncodedImage(base64Data, 0, base64Data.length);
bitmap = fullImage.getBitmap();
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e+"lkllllllllllllllll");
}
catch(Exception e){
System.out.println(e+"lkllllllllllllllll");
}
return fullImage;
}
The way is that i am calling a webservice through which i am getting base64 image string and trying to convert this base64 string to byte array to display image in EncodedImage format.
Are you trying to display an image from the url fetched from the webservice? The url is the image returned from the webservice? If that is so, please try the below code and let me know:
public Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url+ ";deviceside=true;ConnectionUID=S TCP");
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;
}

get image from bytes blackberry

I am developing a blackberry application which retrieves image from the server , some of images are being retreived and other give error in the encodedImage Line
ImageFromUrl _img = new ImageFromUrl(item.getThumbLink());
byte[] bytes = _img.getbitmap();
Bitmap newBitmap = new Bitmap(width, fieldHeight);
if (bytes != null) {
// bitmap = Bitmap.createBitmapFromBytes(bytes, 0,
// bytes.length, Bitmap.SCALE_TO_FIT);
EncodedImage image = EncodedImage.createEncodedImage(bytes,
0, bytes.length);
}
and that's the connection which get the bytes
ImageFromUrl(String url) {
this.url = url;
}
public byte[] getbitmap() {
try {
connection = (HttpConnection) Connector.open(
url + Connection.getBlackBerryConnectionParams(),
Connector.READ, true);
InputStream is = connection.openInputStream();
DataInputStream dis = new DataInputStream(is);
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = dis.read()) != -1) {
// System.out.println((char) ch);
// msg = msg + (char) ch;
bStrm.write(ch);
}
dataArray = bStrm.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return dataArray;
}
how can I solve that to get all images without errors ?
Try this code:
public Bitmap getBitmapFromUrl(String url)
{
Bitmap bitmap=null;
try
{
HttpConnection connection=(HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
InputStream is=connection.openInputStream();
int length=is.available();
byte[] data=new byte[length];
data=IOUtilities.streamToBytes(is);
connection.close();
is.close();
bitmap=Bitmap.createBitmapFromBytes(data,0,data.length,1);
if(bitmap!=null)
return bitmap;
else
return bitmap=Bitmap.getBitmapResource("noimage.png");
}
catch (Exception e)
{
return bitmap=Bitmap.getBitmapResource("noimage.png");
}
}

How to get bitmap from URL in Blackberry

I want to get the Bitmap from URL like -
"https://graph.facebook.com/100003506521332/picture"
I tried how-i-can-display-images-from-url-in-blackberry . But its showing http error 302 .It dont showing the Bitmap. How to resolve the problem ?.
String url = "https://graph.facebook.com/100003506521332/picture";
try
{
bitmap = globleDeclaration.getLiveImage(url, 50, 50);
bitmapField.setBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
Dialog.alert(e.getMessage());
}
public Bitmap getLiveImage(String url,int width,int height) throws IOException
{
Bitmap bitmap = null;
try
{
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=httpconnection.getHeaderField("location");
if(location!=null){
httpconnection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = httpconnection.openInputStream();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = httpconnection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
byte[] dataArray = result.getBytes();
encodeImageBitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
}
catch (final Exception ex)
{
System.out.print("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
finally
{
try
{
inputStream.close();
inputStream = null;
httpconnection.close();
httpconnection = null;
}
catch(Exception e){}
}
return bitmap;
}
If you done get responce from this code httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); which is mention in above answer than u can also use alternative solution for that..
You can pass your your id here http://graph.facebook.com/100003506521332/?fields=picture&type=large than you will get one json responce like that {"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/70678_100003506521332_1415569305_n.jpg"}
parse this json and get which you want exaclty .. than you will get responce using httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); also .
if you dont want larger image than remove &type=large from the above url.
//YOUR PACKAGE NAME
package ...........;
//*************************
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.Bitmap;
public class Util_ImageLoader {
public static Bitmap getImageFromUrl(String url) {
Bitmap bitmap = null;
try {
String bitmapData = getDataFromUrl(url);
bitmap = Bitmap.createBitmapFromBytes(bitmapData.getBytes(), 0,
bitmapData.length(), 1);
} catch (Exception e1) {
e1.printStackTrace();
}
return bitmap;
}
private static String getDataFromUrl(String url) {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0;
int ch = 0;
try {
c = (HttpConnection) Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
is.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
return b.toString();
}
}
copy this to your package....
Now, to use this class do like this>>>>>>>>
CREATE BITMAP OBJECT:
Bitmap IMAGE;
After That:
IMAGE=Util_ImageLoader.getImageFromUrl("https://graph.facebook.com/100003506521332/picture");
By the way, I think you have missed extension
like JPG,PNG, on your URL.... Check That
Now, add your bitmap where you would like to display the image......
ENJOY!
add(IMAGE);

Retriving url from webservice and how to connect to that url

i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if simulator is running
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}

Blackberry send a HTTPPost request

i am developing and app for blackberry and i need to send a Http Post Request to my server. I'm using the simulator in order to test my app and i found this code in order to send request:
http://vasudevkamath.techfiz.com/general/posting-data-via-http-from-blackberry/
But i can't get it work, because it fails in this line:
int rc = _httpConnection.getResponseCode();
Any idea?
thanks
Here is a sample code on how to send a POST request:
HttpConnection c = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = c.openOutputStream();
os.write(request.getBytes("UTF-8"));
os.flush();
os.close();
InputStream is = c.openInputStream();
Just make sure you use this code in a separate thread.
public static ResponseBean sendRequestAndReceiveResponse(String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if you are using simulator
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}
I know this question is pretty old and OP probably solved it by now, but I've just run into the same problem and managed to fix it!
You need to append ;deviceside=true to your URL.
So for example, your URL will change from "http://example.com/directory/submitpost.php" to "http://example.com/directory/submitpost.php;deviceside=true".
I found this here: http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879
My POST request was timing out after 3 minutes when I did not have this (See My Comment), but it works fine with this appended to the url.
I would also recommend using ConnectionFactory. Here's some of my code:
Network.httpPost("http://example.com/directory/submitpost.php;deviceside=true", paramNamesArray, paramValsArray)
public static void httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
ConnectionFactory conFactory = new ConnectionFactory();
conFactory.setTimeLimit(1000);
HttpConnection conn = (HttpConnection) conFactory.getConnection(urlStr).getConnection();
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < paramName.length; i++) {
sb.append(paramName[i]);
sb.append("=");
sb.append(paramVal[i]);
sb.append("&");
}
byte[] postData = sb.toString().getBytes("UTF-8");
conn.setRequestProperty("Content-Length",new Integer(postData.length).toString());
OutputStream out = conn.openOutputStream();
out.write(postData);
//out.flush(); //Throws an Exception for some reason/Doesn't do anything anyways
out.close();
//This writes to our connection and waits for a response
if (conn.getResponseCode() != 200) {
throw new Exception(conn.getResponseMessage());
}
}
Not sure about the site you posted, but I've successfully used the sample ConnectionFactory code provided on the blackberry site.
http://supportforums.blackberry.com/t5/Java-Development/Sample-Code-Using-the-ConnectionFactory-class-in-a-BrowserField/ta-p/532860
Just make sure not to invoke the connection on the EventThread.
That's how you add parameters, Full answer is here:
StringBuffer postData = new StringBuffer();
httpConn = (HttpConnection) Connector.open("https://surveys2.kenexa.com/feedbacksurveyapi/login?");
httpConn.setRequestMethod(HttpConnection.POST);
postData.append("username="+username);
postData.append("&password="+pass);
postData.append("&projectcode="+projectid);
String encodedData = postData.toString();
httpConn.setRequestProperty("Content-Language", "en-US");
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length",(new Integer(encodedData.length())).toString());
byte[] postDataByte = postData.toString().getBytes("UTF-8");
OutputStream out = httpConn.openOutputStream();
out.write(postDataByte);
out.close();
httpConn.getResponseCode();

Resources