473,326 Members | 2,168 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Why the image is not displayed in the imageItem?

108 100+
I used the Nokia sample codes for Google Map. It has retrieveStaticImage method which loads and returns an Image. I them loaded the image to an ImageItem but I get an exception everytime..
Here are my codes...

Codes for GoogleMaps class
<CODE>
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;

public class GoogleMaps implements Runnable{
private static final String URL_UNRESERVED =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789-_.~";
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
Image image;
int width;
int height;
double lat;
double lng;
int zoom;
String format;
ImageItem imagecmpt;
// these 2 properties will be used with map scrolling methods. You can remove them if not needed
public static final int offset = 268435456;
public static final double radius = offset / Math.PI;

private String apiKey = null;

public GoogleMaps(String key,int width, int height, double lat, double lng, int zoom,
String format,ImageItem img) {
this.width=width;
this.height=height;
this.lat=lat;
this.lng=lng;
this.zoom=zoom;
this.format=format;
apiKey = key;

}

public double[] geocodeAddress(String address) throws Exception {
byte[] res = loadHttpFile(getGeocodeUrl(address));
String[] data = split(new String(res), ',');

if (!data[0].equals("200")) {
int errorCode = Integer.parseInt(data[0]);
throw new Exception("Google Maps Exception: " + getGeocodeError(errorCode));
}

return new double[] {
Double.parseDouble(data[2]), Double.parseDouble(data[3])
};
}

public Image retrieveStaticImage() throws IOException {
byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, zoom, format));
System.out.println("Address is "+getMapUrl(width, height, lng, lat, zoom, format));
for (int i=0;i<imageData.length;i++){
System.out.println(imageData[i]);
}
return Image.createImage(imageData, 0, imageData.length);
}

private static String getGeocodeError(int errorCode) {
switch (errorCode) {
case 400:
return "Bad request";
case 500:
return "Server error";
case 601:
return "Missing query";
case 602:
return "Unknown address";
case 603:
return "Unavailable address";
case 604:
return "Unknown directions";
case 610:
return "Bad API key";
case 620:
return "Too many queries";
default:
return "Generic error";
}
}

private String getGeocodeUrl(String address) {
return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=csv&key="
+ apiKey;
}

private String getMapUrl(int width, int height, double lng, double lat, int zoom, String format) {
return "http://maps.google.com/staticmap?center=" + lat + "," + lng + "&format="
+ format + "&zoom=" + zoom + "&size=" + width + "x" + height + "&key=" + apiKey;
}

private static String urlEncode(String str) {
StringBuffer buf = new StringBuffer();
byte[] bytes = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(str);
bytes = bos.toByteArray();
} catch (IOException e) {
// ignore
}
for (int i = 2; i < bytes.length; i++) {
byte b = bytes[i];
if (URL_UNRESERVED.indexOf(b) >= 0) {
buf.append((char) b);
} else {
buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(HEX[b & 0x0f]);
}
}
return buf.toString();
}

private static byte[] loadHttpFile(String url) throws IOException {
byte[] byteBuffer;

HttpConnection hc = (HttpConnection) Connector.open(url);
try {
hc.setRequestMethod(HttpConnection.GET);
InputStream is = hc.openInputStream();
try {
int len = (int) hc.getLength();
if (len > 0) {
byteBuffer = new byte[len];
int done = 0;
while (done < len) {
done += is.read(byteBuffer, done, len - done);
}
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int count;
while ( (count = is.read(buffer)) >= 0 ) {
bos.write(buffer, 0, count);
}
byteBuffer = bos.toByteArray();
}
} finally {
is.close();
}
} finally {
hc.close();
}

return byteBuffer;
}

private static String[] split(String s, int chr) {
Vector res = new Vector();

int curr;
int prev = 0;

while ( (curr = s.indexOf(chr, prev)) >= 0 ) {
res.addElement(s.substring(prev, curr));
prev = curr + 1;
}
res.addElement(s.substring(prev));

String[] splitted = new String[res.size()];
res.copyInto(splitted);

return splitted;
}

public void run() {
try{
//throw new UnsupportedOperationException("Not supported yet.");
imagecmpt.setImage(retrieveStaticImage());
}
catch(Exception e){
System.out.println("Error ......."+e);
}
}
}

</CODE>

codes for midlet
<CODE>
public void commandAction(Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
} else if (command == okCommand) {
// write pre-action user code here

// write post-action user code here

GoogleMaps cMz=new GoogleMaps("ABQIAAAADEQoVqbqS5pT4ahHSLALyBT8PMUw5z 7_OLJoE1lh2VQyfb-WOxTwS9t9mrSq_flhdPeVGOQrxXuCFQ",10, 10, 10, 10, 1, "roadmap", imageItem);

Thread th=new Thread(cMz);
th.run();
Display display=getDisplay ();


}
}
// write post-action user code here
}

</CODE>

My output:::

Starting emulator in execution mode
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Running in the identified_third_party security domain
Warning: To avoid potential deadlock, operations that may block, such as
networking, should be performed in a different thread than the
commandAction() handler.

I have used an external thread but yet it keeps telling me to use another thread..
How can I sort this out?
Nov 30 '10 #1
0 1103

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: mrique | last post by:
hi My readers that are lotus note user receive the mails I send using cdonts with image displayed as attachement in place of inline. I read...
2
by: Fabio Negri Cicotti [MCP] | last post by:
Hi all. How do I do to display a picture on e-mail's body when visualized using Outlook Express? I've set the properties bellow but till now I've got the image shown as that box with a red...
1
by: ApexData | last post by:
Hello I am in the early stages of my project development, and want to make sure that I am approaching the issue of image display correctly. Access2000. I have one table and a bound single...
1
by: =?Utf-8?B?Umlz?= | last post by:
Hi, I have an image displayed in a PictureBox and the displayed image is resized and centred. When I click on the image, I can get the coordinates relative to the PictureBox but I would like the...
4
by: si_owen | last post by:
Hi All, I have created an application that allows users to upload images to their listed events. When a user views their event their uploaded image is also displayed. However does anyone know...
8
by: Haines Brown | last post by:
I want a hot text string to display an image only when hovered. In the body: .... <a id="link-a" href="#nogo"> <img id="photo" src="..." />hot text </a> ....
2
by: mukeshrasm | last post by:
Hi I am printing some text on image dynamically. I am setting the font size and type dynamically and then displaying to other page. Thing is that it is not displaying the image when I click submit...
5
by: aewhale | last post by:
I am putting together a website for my company's Email Security tool, SpamZapper. The problem is that the webpage on http://www.spamzapper.us/features It displays correctly with Firefox. However...
0
by: Lou O | last post by:
I have browsed and seen several posts on the subject but my issue seems to be unique. I have an image control on a form that updates on the after update event of a list box on the control. For...
11
by: NDayave | last post by:
How Do, I am using custom message boxes to make them much more aesthetically pleasing. On this form, there are 4 images for "Question", "Information", "Critical" and "Exclamation". I found the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.