Images are loading on simulater but not on Blackberry device - blackberry

I am using following code to download images from server
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+ ConnectionType.getConnectionType());
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 ConnetionType class is as follows
public class ConnectionType {
public static String getConnectionType()
{
String connectionString = null;
if (DeviceInfo.isSimulator())
{
connectionString = "";
return connectionString;
}
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
return connectionString;
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null)
{
connectionString = ";deviceside=true";
return connectionString;
}
else
{
connectionString=carrierUid;
return connectionString;
}
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
return connectionString;
}
else
{
connectionString = ";deviceside=true";
return connectionString;
]
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The UID used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if (records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
//otherwise, use the UID to construct a valid carrier BIB-S
String carrierUid= records[currentRecord].getUid();
String extension = ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
return extension;
}
}
}
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("wptcp"))
{
String carrierUid= records[currentRecord].getUid();
String extension = ";ConnectionUID="+carrierUid;
return extension;
}
}
return null;
}
}
Images are displaying fine on simulater but when I run this on my device No image displayed .Please suggest where I am missing.
Thanks!!!

Related

Background Application unable to display UI when receive push notification

Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.

Get suffix string for BlackBerry connection on 4.6.1?

I'm trying to develop an application which uses HttpRequest for requesting a web page. The problem is that I still can't find the right way to get the suffix in the connection string for OS 4.6.1.
Thanks.
The links I believe I used to create my connection strings, pre OS 5.0, were these two:
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879
http://docs.blackberry.com/en/developers/deliverables/34480/Network_transport_options_1293321_11.jsp
BlackBerry of course supports several different transports (Wifi, WAP, BIS, etc.). You probably want to decide which transport you would like to use, and create your connection string depending on which transports are available at any one time, and on your priority.
Here's some more sample code to download from blackberry.com that helps build connection string suffixes. See the attachment links near the bottom for the actual downloads.
Also, if you're in a time crunch, and don't have time to read the resources I listed in my other answer, and just want some quick code, I remember there was an implementation in BlackBerry's original Facebook SDK that looked close to what I wrote myself (sorry, I can't post that code I wrote, because it's my client's). But, the Facebook SDK implementation appears to be free to publish. I can't find a link to it anymore, but I'll paste it below for your enjoyment:
/**
* Copyright (c) E.Y. Baskoro, Research In Motion Limited.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This License shall be included in all copies or substantial
* portions of the Software.
*
* The name(s) of the above copyright holders shall not be used
* in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*
*/
package com.blackberry.util.network;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.blackberry.util.log.Logger;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Branding;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.WLANInfo;
public class HttpConnectionFactory {
public static final int TRANSPORT_WIFI = 1;
public static final int TRANSPORT_BES = 2;
public static final int TRANSPORT_BIS = 4;
public static final int TRANSPORT_DIRECT_TCP = 8;
public static final int TRANSPORT_WAP2 = 16;
public static final int TRANSPORT_SIM = 32;
public static final int TRANSPORTS_ANY = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int TRANSPORTS_AVOID_CARRIER = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_SIM;
public static final int TRANSPORTS_CARRIER_ONLY = TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int DEFAULT_TRANSPORT_ORDER[] = { TRANSPORT_SIM, TRANSPORT_WIFI, TRANSPORT_BIS, TRANSPORT_BES, TRANSPORT_WAP2, TRANSPORT_DIRECT_TCP };
private static final int TRANSPORT_COUNT = DEFAULT_TRANSPORT_ORDER.length;
// private static ServiceRecord srMDS[], srBIS[], srWAP2[], srWiFi[];
private static ServiceRecord srWAP2[];
private static boolean serviceRecordsLoaded = false;
private int transports[];
private int lastTransport = -1;
protected Logger log = Logger.getLogger(getClass());
public HttpConnectionFactory() {
this(0);
}
public HttpConnectionFactory(int allowedTransports) {
this(transportMaskToArray(allowedTransports));
}
public HttpConnectionFactory(int transportPriority[]) {
if (!serviceRecordsLoaded) {
loadServiceBooks(false);
}
transports = transportPriority;
}
public static String getUserAgent() {
StringBuffer sb = new StringBuffer();
sb.append("BlackBerry");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion());
sb.append(" Profile/");
sb.append(System.getProperty("microedition.profiles"));
sb.append(" Configuration/");
sb.append(System.getProperty("microedition.configuration"));
sb.append(" VendorID/");
sb.append(Branding.getVendorId());
return sb.toString();
}
public static String getProfile() {
StringBuffer sb = new StringBuffer();
sb.append("http://www.blackberry.net/go/mobile/profiles/uaprof/");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion().substring(0, 3)); //RDF file format is 4.5.0.rdf (does not include build version)
sb.append(".rdf");
return sb.toString();
}
public HttpConnection getHttpConnection(String pURL) {
return getHttpConnection(pURL, null, null);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers) {
return getHttpConnection(pURL, headers, null);
}
public HttpConnection getHttpConnection(String pURL, byte[] data) {
return getHttpConnection(pURL, null, data);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers, byte[] data) {
if ((pURL.length() > 5) && pURL.startsWith("cod://")) {
return new LocalHttpConnection(pURL);
}
int curIndex = 0;
HttpConnection con = null;
while ((con = tryHttpConnection(pURL, curIndex, headers, data)) == null) {
try {
curIndex = nextTransport(curIndex);
} catch (HttpConnectionFactoryException e) {
e.printStackTrace();
break;
} finally {
}
}
if (con != null) {
setLastTransport(transports[curIndex]);
}
return con;
}
private int nextTransport(int curIndex) throws HttpConnectionFactoryException {
if ((curIndex >= 0) && (curIndex < transports.length - 1)) {
return curIndex + 1;
} else {
throw new HttpConnectionFactoryException("No more transport available.");
}
}
private HttpConnection tryHttpConnection(String pURL, int tIndex, HttpHeaders headers, byte[] data) {
HttpConnection con = null;
OutputStream os = null;
log.debug("Trying " + getTransportName(transports[tIndex]) + "... ");
switch (transports[tIndex]) {
case TRANSPORT_SIM:
try {
con = getSimConnection(pURL, false);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_WIFI:
try {
con = getWifiConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BES:
try {
con = getBesConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BIS:
try {
con = getBisConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_DIRECT_TCP:
try {
con = getTcpConnection(pURL);
} catch (IOException e) {
} finally {
break;
}
case TRANSPORT_WAP2:
try {
con = getWap2Connection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
}
log.debug("con = " + con);
if (con != null) {
try {
log.debug("url = " + con.getURL());
//add headers to connection
if (headers != null) {
int size = headers.size();
for (int i = 0; i < size;) {
String header = headers.getPropertyKey(i);
String value = headers.getPropertyValue(i++);
if (value != null) {
con.setRequestProperty(header, value);
}
}
}
// post data
if (data != null) {
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(data.length));
os = con.openOutputStream();
os.write(data);
} else {
con.setRequestMethod(HttpConnection.GET);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return con;
}
public int getLastTransport() {
return lastTransport;
}
public String getLastTransportName() {
return getTransportName(getLastTransport());
}
private void setLastTransport(int pLastTransport) {
lastTransport = pLastTransport;
}
private HttpConnection getSimConnection(String pURL, boolean mdsSimulatorRunning) throws IOException {
if (DeviceInfo.isSimulator()) {
if (mdsSimulatorRunning) {
return getConnection(pURL, ";deviceside=false", null);
} else {
return getConnection(pURL, ";deviceside=true", null);
}
}
return null;
}
private HttpConnection getBisConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(4 /* CoverageInfo.COVERAGE_BIS_B */)) {
return getConnection(pURL, ";deviceside=false;ConnectionType=mds-public", null);
}
return null;
}
private HttpConnection getBesConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(2 /* CoverageInfo.COVERAGE_MDS */)) {
return getConnection(pURL, ";deviceside=false", null);
}
return null;
}
private HttpConnection getWifiConnection(String pURL) throws IOException {
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
return getConnection(pURL, ";interface=wifi", null);
}
return null;
}
private HttpConnection getWap2Connection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */) && (srWAP2 != null) && (srWAP2.length != 0)) {
return getConnection(pURL, ";deviceside=true;ConnectionUID=", srWAP2[0].getUid());
}
return null;
}
private HttpConnection getTcpConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */)) {
return getConnection(pURL, ";deviceside=true", null);
}
return null;
}
private HttpConnection getConnection(String pURL, String transportExtras1, String transportExtras2) throws IOException {
StringBuffer fullUrl = new StringBuffer();
fullUrl.append(pURL);
if (transportExtras1 != null) {
fullUrl.append(transportExtras1);
}
if (transportExtras2 != null) {
fullUrl.append(transportExtras2);
}
return (HttpConnection) Connector.open(fullUrl.toString());
}
public static void reloadServiceBooks() {
loadServiceBooks(true);
}
private static synchronized void loadServiceBooks(boolean reload) {
if (serviceRecordsLoaded && !reload) {
return;
}
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
Vector mdsVec = new Vector();
Vector bisVec = new Vector();
Vector wap2Vec = new Vector();
Vector wifiVec = new Vector();
if (!serviceRecordsLoaded) {
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
String cid, uid;
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
if ((cid.indexOf("wptcp") != -1) && (uid.indexOf("wap2") != -1) && (uid.indexOf("wifi") == -1) && (uid.indexOf("mms") == -1)) {
wap2Vec.addElement(myRecord);
}
}
}
srWAP2 = new ServiceRecord[wap2Vec.size()];
wap2Vec.copyInto(srWAP2);
wap2Vec.removeAllElements();
wap2Vec = null;
serviceRecordsLoaded = true;
}
}
public static int[] transportMaskToArray(int mask) {
if (mask == 0) {
mask = TRANSPORTS_ANY;
}
int numTransports = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
numTransports++;
}
}
int transports[] = new int[numTransports];
int index = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
transports[index++] = DEFAULT_TRANSPORT_ORDER[i];
}
}
return transports;
}
private static String getTransportName(int transport) {
String tName;
switch (transport) {
case TRANSPORT_WIFI:
tName = "WIFI";
break;
case TRANSPORT_BES:
tName = "BES";
break;
case TRANSPORT_BIS:
tName = "BIS";
break;
case TRANSPORT_DIRECT_TCP:
tName = "TCP";
break;
case TRANSPORT_WAP2:
tName = "WAP2";
break;
case TRANSPORT_SIM:
tName = "SIM";
break;
default:
tName = "UNKNOWN";
break;
}
return tName;
}
}

How i can display images from URL in blackberry?

i have simple url of image, i want to display that image in Bitmap Field.
this is my class..But it will is not give any result.
public class UrlToImage
{
public static Bitmap _bmap;
UrlToImage(String url)
{
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
try
{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
dataArray = result.getBytes();
}
catch (final Exception ex)
{ }
finally
{
try
{
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){}
}
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield
int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(480));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(360));//width
bitmap = bitmap.scaleImage32(multW,multH);
_bmap=bitmap.getBitmap();
}
public Bitmap getbitmap()
{
return _bmap;
}
}
Thanx in advance.
Try this but here url extension is important.
if your mobile using wifi then ";interface=wifi" this is working otherwise it wont work so for url extensions plese verify following url
For url extensions Link
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");
rc = httpConnection.getResponseCode();
if (rc == HttpConnection.HTTP_OK)
{
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;
}
I am getting solution of this Question..
See this url for All connection: BlackBerry simulator can connect to web service, but real device can't
public final class MyScreen extends MainScreen
{
String url="";
public MyScreen()
{
setTitle("MyTitle");
BitmapField pic = new BitmapField(connectServerForImage(url));
this.add(pic);
}
public static Bitmap connectServerForImage(String url)
{
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
httpConnection = (HttpConnection) Connector.open(url+ ";interface=wifi",Connector.READ_WRITE, true);
}
else
{
httpConnection = (HttpConnection) Connector.open(url+";deviceside=true", Connector.READ_WRITE, true);
}
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;
}
}

Blackberry: consuming a restful web service

public void consumeIt(){
HttpConnection con = null;
InputStream is = null;
try {
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
con = (HttpConnection) Connector.open(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = is.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
final String result = rawResponse.toString();
System.out.println("result:" + result);
}
catch (final Exception ex) {
System.out.println("error:" + ex.getMessage());
}
finally {
try {
is.close();
is = null;
con.close();
con = null;
}
catch(Exception e){}
}
}
I found the code above that is supposed to grab the xml data returned by the api, however I can't seem to get it working. The system print out with "poo" shows up, but not the "Works here." I have no idea what's wrong. I'm running it in a 9700 simulator.
Why is it so complicated to connect to a web service!
Please read about BB transports and networking.
For quick fix use this url:
"http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC;deviceside=true"
instead of yours.
I already answer this type of errors occurred because of Network extensions
just see this answer this and take changes in your code absolutely it will work
please check the following link and take directions
https://stackoverflow.com/a/8575601/914111
after importing two classes into your project just change your code as following way
public void consumeIt(){
HttpConnection con = null;
InputStream is = null;
try {
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
HttpConnectionFactory factory = new HttpConnectionFactory(0);
con = factory.getHttpConnection(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = is.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
final String result = rawResponse.toString();
System.out.println("result:" + result);
}
catch (final Exception ex) {
System.out.println("error:" + ex.getMessage());
}
finally {
try {
is.close();
is = null;
con.close();
con = null;
}
catch(Exception e){}
}
}
i got output as on my console like
result:<?xml version="1.0" encoding="UTF-8"?> <ResultSet version="1.0"><Error>0</Error><ErrorMessage>No error</ErrorMessage><Locale>us_US</Locale><Quality>87</Quality><Found>1</Found><Result><quality>85</quality><latitude>38.898717</latitude><longitude>-77.035974</longitude><offsetlat>38.898590</offsetlat><offsetlon>-77.035971</offsetlon><radius>500</radius><name></name><line1>1600 Pennsylvania Ave NW</line1><line2>Washington, DC 20006</line2><line3></line3><line4>United States</line4><house>1600</house><street>Pennsylvania Ave NW</street><xstreet></xstreet><unittype></unittype><unit></unit><postal>20006</postal><neighborhood></neighborhood><city>Washington</city><county>District of Columbia</county><state>District of Columbia</state><country>United States</country><countrycode>US</countrycode><statecode>DC</statecode><countycode>DC</countycode><uzip>20006</uzip><hash>B42121631CCA2B89</hash><woeid>12765843</woeid><woetype>11</woetype></Result></ResultSet> <!-- gws14.maps.sg1.yahoo.com uncompressed/chunked Thu Dec 22 21:22:38 PST 2011 --> <!-- wws2.geotech.sg1.yahoo.com uncompressed/chunked Thu Dec 22 21:22:38 PST 2011 -->
You can try this.
public void consumeIt()
{
HttpConnection con = null;
InputStream is = null;
String desiredEncoding = "ISO-8859-1";
StringBuffer returnStringBuffer = new StringBuffer();
OutputStream os=null;
try
{
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
HttpConnectionFactory factory = new HttpConnectionFactory(0);
con = factory.getHttpConnection(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
int ch;
String contenttype = httpConnection.getHeaderField("Content-Type");
if (contenttype != null)
{
contenttype = contenttype.toUpperCase();
if (contenttype.indexOf("UTF-8") != -1)
{
desiredEncoding = "UTF-8";
}
}
InputStreamReader isr = new InputStreamReader(inputStream,desiredEncoding);
while ((ch = isr.read()) != -1)
{
returnStringBuffer.append((char) ch);
}
result=returnStringBuffer.toString();
System.out.println("Result........"+result);
}
catch (final Exception ex)
{
System.out.println("error:" + ex.getMessage());
}
finally
{
try
{
is.close();
is = null;
con.close();
con = null;
}
}
}

Download and show image on a BlackBerry

I have to develop a url which involves downloading image from url and show in blackberry stimulator..Can anyone help me in this regard???
This code 'll connect the given URL and returns Bitmap object
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;
}
U can create a bimapfield and asign this bitmap as
BitmapField bmpFld1=new BitmapField(connectServerForImage(Url));
For base 64 string decoding
try {
mapaByte = Base64InputStream.decode(imagenB64);
Bitmap mapa64 = Bitmap.createBitmapFromBytes(mapaByte, 0, -1, 1);
mapa.setBitmap(mapa64);
}
catch (Exception e) {}

Resources