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;
}
}
Related
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!!!
Is it possible to clear the amount packets sent/ received and start from 0 again??
The Code to get sent or received packets:
long no_of_packet_Sent = RadioInfo.getNumberOfPacketsSent();
long no_of_packet_Received = RadioInfo.getNumberOfPacketsReceived();
I never found the answer to this but another option is to write the data to a text file then minus the data in the text file from the "get number of packets" .
private static String fileFormatString(String filename) {
return filename.replace(" ".charAt(0),"_".charAt(0));
}
public static String readTextFile(String fName) {
fName = fileFormatString(fName);
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println("Error on read: "+fName+" - " + e.getMessage());
} finally {
try {
if (null != is) is.close();
if (null != fconn) fconn.close();
} catch (IOException e) {
System.out.println("Error on read IO: "+fName+" - " + e.getMessage());
}
}
return result;
}
public static void writeTextFile(String fName, String text) {
fName = fileFormatString(fName);
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (fconn.exists());
if (!fconn.exists()) fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println("Error on write: "+fName+" - " + e.getMessage());
} finally {
try {
if (null != os) os.close();
if (null != fconn) fconn.close();
} catch (IOException e) {
System.out.println("Error on write IO: "+fName+" - " + e.getMessage());
}
}
}
long no_of_packet = RadioInfo.getNumberOfPacketsSent()+RadioInfo.getNumberOfPacketsReceived();
DTHelper.writeTextFile(text_file_name,""+no_of_packet );
String readnumberofkbytes=readTextFile(text_file_name);
long Longreadnumberofbytes = Long.parseLong(readnumberofbytes);
long CurrentNumberofDataUsed= no_of_packet -Longreadnumberofbytes;
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;
}
}
}
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) {}
please give me a sample code for read/write text file in blackberry application.
My code snippet for string read/write files:
private String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
private void writeTextFile(String fName, String text) {
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != os)
os.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Using
FileConnection Interface