myReverseGeocode is not starting. - blackberry

In below code when i call myReverseGeocode address = new myReverseGeocode(latitude, longitude); , gpsData.append(address.temp); always show "null"
public HelloBlackBerryScreen() {
super( MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR );
setTitle( "Get Address" );
ButtonField buttonField_1 = new ButtonField( "Get GPS", ButtonField.CONSUME_CLICK | ButtonField.FIELD_RIGHT );
add( buttonField_1 );
buttonField_1.setChangeListener( new FieldChangeListener() {
public void fieldChanged( Field arg0, int arg1 ) {
Criteria c = new Criteria();
try {
LocationProvider lp = LocationProvider.getInstance(c);
if( lp!=null )
{
lp.setLocationListener(new LocationListenerImpl(), 3, 1, 1);
myReverseGeocode address = new myReverseGeocode(latitude, longitude);
gpsData.append(address.temp);
myloc = gpsData.toString();
}
} catch (LocationException le) {
;
}
myReverseGeocode.java
package mypackage;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Landmark;
import net.rim.device.api.lbs.Locator;
import net.rim.device.api.lbs.LocatorException;
public class myReverseGeocode {
private Thread reverseGeocode;
public AddressInfo addrInfo = null;
String temp;
public myReverseGeocode(final double lt, final double ln)
{
Runnable thread = new Runnable()
{
public void run()
{
int latitude = (int)(lt * 100000);
int longitude = (int)(ln * 100000);
try
{
Landmark[] results = Locator.reverseGeocode(latitude, longitude, Locator.ADDRESS );
if ( results != null && results.length > 0 )
temp = "inside if";
else
temp = "in else";
}
catch ( LocatorException lex )
{
}
}
};
reverseGeocode = new Thread(thread);
reverseGeocode.setPriority(Thread.MIN_PRIORITY);
reverseGeocode.start();
}
}

You always get temp as null because you ask for it almost immediatelly after the Thread (that is started in constructor of the myReverseGeocode) has been started. You need to redesign your myReverseGeocode to udate the UI of the screen after an actual temp value is got.

Related

Blackberry j2me location services

I'm writing my first BB app with J2ME. I found a code snippet that describes how to get GPS coordinates. I'm getting a null pointer exception (on the phone) but none on the emulator and I'm not sure why.
I would appreciate any help.
Code below:
try
{
// Set criteria for selecting a location provider:
Criteria cr= new Criteria();
cr.setCostAllowed(true);
cr.setSpeedAndCourseRequired(true);
// Get an instance of the provider
LocationProvider lp= LocationProvider.getInstance(cr);
// Request the location, setting a 60 second timeout
Location l = lp.getLocation(300); //always times out
Coordinates c = l.getQualifiedCoordinates();
double longitude = 0;
double latitude = 0;
float course = l.getCourse();
float speed = l.getSpeed();
long timestamp = l.getTimestamp();
if(c != null )
{
// Use coordinate information
latitude = c.getLatitude();
longitude = c.getLongitude();
}
System.out.println("Lon" + longitude + " Lat "+ latitude + " course "+course+" speed "+speed+" timestamp "+timestamp);
}
catch(LocationException le)
{
System.out.println("Location exception "+le);
}
catch(InterruptedException ie)
{
System.out.println("Interrupted exception "+ie);
}
use this code
public class handleGPS{
static GPSThread gpsThread;
public static double latitude ;
public static double longitude;
public handleGPS(){
gpsThread = new GPSThread();
gpsThread.start();
}
private static class GPSThread extends Thread{
public void run() {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
try {
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
latitude = myLocation.getQualifiedCoordinates().getLatitude();
longitude = myLocation.getQualifiedCoordinates().getLongitude();
System.out.print("latitude= "+latitude+" longitude="+longitude);
}
catch ( InterruptedException iex ) {
return;
}
catch ( LocationException lex ) {
return;
}
}catch ( LocationException lex ) {
return;
}
return;
}
}
}
then on your main class, call the above class
handleGPS handleGPS=new handleGPS();
int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");
if(m_bbHandle>0){
Dialog.alert("GPS not found");
}
else{
Dialog.alert("GPS found");
//your code
}

Blackberry Location Service fails on real device?

I've been trying to get longitude and latitude values using Blackberry's GPS listener. My device is a blackberry torch. The simulator I use also is a blackberry torch. The GPS listener seems to be working on the sim, but once on a real device it fails. When I say fail, it does not pick up longitude and latitude values, rather, it struggles to even connect to the GPS. I checked my options menu, and I'm able to pick up long and lat values from the location settings, so why would my app not be able to do it?
I call the class handleGPS in another class, i.e by doing this:
new handleGPS();
As I said, using the SIM I the provider finds my location after about 10 seconds. On the real device, I debug it and it does reach this statement (as the System.out's are printed)
try {
lp = LocationProvider.getInstance(cr);
System.out.println("location Provider");
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
//lp.setLocationListener(listener, interval, timeout, maxAge)
System.out.println("location Provider after listener");
} catch (LocationException e) {
e.printStackTrace();
}
However no values get returned. Below is my code.
GPS class:
public class handleGPS extends TimerTask {
//Thread t = new Thread(new Runnable() {
private Timer timer;
LocationProvider lp = null;
public handleGPS()
{
timer =new Timer();
System.out.println("timer");
GPS();
//timer.schedule(this, 0, 10000);
timer.schedule(this, 1000);
}
public void GPS() {
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
//cr.setPreferredResponseTime(1000);
System.out.println("GPS ()");
try {
lp = LocationProvider.getInstance(cr);
System.out.println("location Provider");
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
//lp.setLocationListener(listener, interval, timeout, maxAge)
System.out.println("location Provider after listener");
} catch (LocationException e) {
e.printStackTrace();
}
}
// });
public void run() {
// TODO Auto-generated method stub
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
}
}
And here is the handler:
public class handleGPSListener implements LocationListener {
Coordinates c = null;
private static double lat=0.00;
private static double lon=0.00;
Database sqliteDB;
String username;
public static final String NAMESPACE = "http://tempuri.org/";
public String URL = "http://77.245.77.195:60010/Webservice/IDLMobile.asmx?WSDL";
public static final String SOAP_ACTION = "http://tempuri.org/Get_OfferCount_By_Location";
public static final String METHOD_NAME = "Get_OfferCount_By_Location";
private double x,y;
public void locationUpdated(LocationProvider loc, Location location) { //method to update as the location changes.
System.out.println("class handle GPS Listener");
if (loc == null) { //condition to check if the location information is null.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS not supported!"); //dialog box to alert gps is not started.
System.out.println("Problem 1");
return;
}
});
} else { //if not checked.
System.out.println("OK");
switch (loc.getState()) { //condition to check state of the location.
case (LocationProvider.AVAILABLE): //condition to check if the location is available.
System.out.println("Provider is AVAILABLE");
try {
location = loc.getLocation(-1); //location to get according to user present.
} catch (LocationException e) {
return;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (location != null && location.isValid()) { //condition to check if the location is not null and is valid.
c = location.getQualifiedCoordinates(); //to get the coordinates of the location.
}
if (c != null) { //condition to check if the location is not null.
lat = c.getLatitude(); //retrieve the latitude values into variable.
lon = c.getLongitude(); //retrieve the longitude values into variable.
System.out.println("lat and lon"+lat+lon);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
updateFields();
getValues();
// Dialog.alert(lat+"GPS supported!"+lon);
return;
}
private void getValues() {
// TODO Auto-generated method stub
try {
URI uri = URI
.create("file:///SDCard/"
+ "database3.db"); //database3 to retrieve the values from location table.
sqliteDB = DatabaseFactory.open(uri);
Statement st = null;
st = sqliteDB
.createStatement("SELECT Latitude,Longitude FROM Location");//statement to retrieve the lat and lon values.
st.prepare();
Cursor c = st.getCursor();//cursor to point.
Row r;
int i = 0;
while (c.next()) { //loop to execute until there are no values in the cursor.
r = c.getRow(); //store the values in row.
i++;
lat=Double.parseDouble(r.getString(0)); //retrieve the latitude values from the database and store in variable.
lon=Double.parseDouble(r.getString(1)); //retrieve the longitude values from the database and store in variable.
System.out.println(r.getString(0)
+ " Latitude");
System.out.println(r.getString(1)
+ " Longitude");
}
st.close();
sqliteDB.close();
}
catch (Exception e) {
System.out.println(e.getMessage()
+ " wut");
e.printStackTrace();
}
try {
URI uri = URI
.create("file:///SDCard/"
+ "database1.db");
sqliteDB = DatabaseFactory.open(uri);
Statement st = null;
st = sqliteDB
.createStatement("SELECT Name FROM People");
st.prepare();
Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
username=r.getString(0);
System.out.println(r.getString(0)
+ "Name");
}
st.close();
sqliteDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
rpc.addProperty("Username", username);
rpc.addProperty("latitude", String.valueOf(lat));
rpc.addProperty("longitude", String.valueOf(lon));
rpc.addProperty("distance", "1.5");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
HttpTransport ht = new HttpTransport(URL);
ht.debug = true;
try {
ht.call(SOAP_ACTION, envelope);
System.out.println("IN TRY");
SoapObject resultProperties = (SoapObject) envelope
.getResponse();
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(0));
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(1).toString());
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(2).toString());
System.out.println("lat and lon PARSE HERE " + lat+"\n"+lon);
/* here is the notification code */
//ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
//EncodedImage image = EncodedImage.getEncodedImageResource("logosmall.png");
//ApplicationIcon icon = new ApplicationIcon( image );
//ApplicationIndicator indicator = reg.register( icon, false, true);
//indicator.setIcon(icon);
//indicator.setVisible(true);
//setupIndicator();
//setVisible(true, 0);
//NotificationsManager.triggerImmediateEvent(1, 0, 20, null);
//NotificationsManager.
/* end notification code */
} catch (org.xmlpull.v1.XmlPullParserException ex2) {
} catch (Exception ex) {
String bah = ex.toString();
}
}
private void updateFields() {
// TODO Auto-generated method stub
try {
URI myURI = URI
.create("file:///SDCard/"
+ "database3.db");
sqliteDB = DatabaseFactory.open(myURI);
Statement st = null;
Statement oops = null;
st = sqliteDB
.createStatement("SELECT Latitude,Longitude FROM Location");
st.prepare();
Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
x=Double.parseDouble(r.getString(0));
y=Double.parseDouble(r.getString(1));
System.out.println(r.getString(0)
+ " Latitude in update fields");
System.out.println(r.getString(1)
+ " Longitude in update fields");
}
st = sqliteDB
.createStatement("UPDATE Location SET Latitude='"
+ lat
+ "' "
+ "WHERE Latitude="
+ "'" + x + "'" + "");
oops = sqliteDB
.createStatement("UPDATE Location SET Longitude='"
+ lon
+ "' "
+ "WHERE Longitude="
+ "'" + y + "'" + "");
System.out.println("location updated");
System.out
.println("lat and lon values are"
+ lat + lon);
st.prepare();
oops.prepare();
st.execute();
oops.execute();
st.close();
oops.close();
sqliteDB.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
});
}
}
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
if (newState == LocationProvider.OUT_OF_SERVICE) {
// GPS unavailable due to IT policy specification
System.out.println("GPS unavailable due to IT policy specification");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS unavailable due to IT policy specification");
return;
}
});
} else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE) {
// no GPS fix
System.out.println("GPS temporarily unavailable due to IT policy specification");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("no GPS fix");
return;
}
});
}
}
public ApplicationIndicator _indicator;
public static handleGPSListener _instance;
public void setupIndicator() {
//Setup notification
if (_indicator == null) {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
_indicator = reg.getApplicationIndicator();
if(_indicator == null) {
ApplicationIcon icon = new ApplicationIcon(EncodedImage.getEncodedImageResource ("daslogo.png"));
_indicator = reg.register(icon, false, true);
_indicator.setValue(0);
_indicator.setVisible(false);
}
}
}
public void setVisible(boolean visible, int count) {
if (_indicator != null) {
if (visible) {
_indicator.setVisible(true);
_indicator.setValue(count);
} else {
_indicator.setVisible(false);
}
}
}
handleGPSListener () {
}
public static handleGPSListener getInstance() {
if (_instance == null) {
_instance = new handleGPSListener ();
}
return(_instance);
}
public double returnLong(){
return lon;
}
public double returnLat(){
return lat;
}
}
Your handler's locationUpdated method is never being called, right? If you call getLocation directly does it work?
I was unable to get the listener to work correctly and eventually moved to using a timer instead from which I call getLocation...
I suspect that the listener only listens to events and does not create them, i.e. if something asked for the location, the listener will receive it as well, but if nothing asked for the location you get nothing.
In GPS it is wise to never trust the simulator, it lies. :)

Blackberry not able to fetch Latitude and longitude

I need to get the users latitude and longitude to display data in increasing order of distance.
I am using 2 phones in 2 different countries to test the app. It works fine with a bb bold 9700 when used in south asia. But does not with a bb 9650 when used in nyc.
I tried using the bb gps api based classes and also google tower based gps classes.
Both don't seem to work in nyc with bb 9650.I used other location based apps like yelp etc which work perfectly.
Attaching both the codes
Phone GPS
public class GPS_Location
{
private String log;
double longi;
double lati;
public GPS_Location()
{
new LocationTracker();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask
{
private Timer timer;
private LocationProvider provider;
Criteria cr;
public LocationTracker()
{
timer = new Timer();
cr= new Criteria();
resetGPS();
timer.schedule(this, 0, 60000);
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
/*provider.setLocationListener(null, 0, 0, 0);
provider.reset();
provider = null;*/
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
//provider = LocationProvider.getInstance(null);
} catch(Exception e)
{
}
}
public void run()
{
System.out.println("********************");
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("********************latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("********************longitude ::"+longi);
CustomSession.getInstance().setLatitude(lati);
CustomSession.getInstance().setLongitude(longi);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}
cell tower google service
public class JsonGenerator {
public void locating() throws IOException{
byte[] postData = getGPSJsonObject().toString().getBytes();
JSONObject jsonObject = null;
HttpConnection gpsConnection;
DataOutputStream os;
DataInputStream dis;
String gpsString = retrunURLString("http://www.google.com/loc/json");
try {
gpsConnection = (HttpConnection) Connector.open(gpsString);
gpsConnection.setRequestMethod(HttpConnection.POST);
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
.valueOf(postData.length));
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_TYPE,
"application / requestJson");
os = gpsConnection.openDataOutputStream();
os.write(postData);
int rc = gpsConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
return;
}
dis = gpsConnection.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = dis.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
String jsonString = new String(data);
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject locationObject = jsonObject.getJSONObject("location");
if (locationObject.getDouble("latitude") != 0.0
&& locationObject.getDouble("longitude") != 0.0) {
System.out.println("Latitute is =================::::"+locationObject.getDouble("latitude"));
System.out.println("Llongitude is =================::::"+locationObject.getDouble("longitude"));
CustomSession.getInstance().setLatitude(locationObject.getDouble("latitude"));
CustomSession.getInstance().setLongitude(locationObject.getDouble("longitude"));
// Global.horizontal_accuracy = locationObject
// .getDouble("accuracy");
// Global.locAvailable = true;
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public JSONObject getGPSJsonObject() {
JSONObject jsonString = new JSONObject();
try {
jsonString.put("version", "1.1.0");
jsonString.put("host", "maps.google.com");
int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
.toHexString(x)));
jsonString.put("home_mobile_network_code", RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
int radio = RadioInfo.getNetworkType();
if(radio==RadioInfo.NETWORK_CDMA){
jsonString.put("radio_type", "cdma");
}
else{
jsonString.put("radio_type", "gsm");
}
jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
jsonString.put("request_address", true);
jsonString.put("address_language", "en_GB");
CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
.getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
Hashtable map = new Hashtable();
map.put("mobile_country_code", new Integer(Integer
.parseInt(cellInfo.mobileCountryCode)));
map.put("location_area_code",
new Integer(cellInfo.locationAreaCode));
map.put("signal_strength", new Integer(cellInfo.signalStrength));
map.put("cell_id", new Integer(cellInfo.cellID));
map.put("age", new Integer(0));
map.put("mobile_network_code", new Integer(
cellInfo.mobileNetworkCode));
JSONArray array = new JSONArray();
array.put(0, map);
jsonString.put("cell_towers", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
public static String retrunURLString(String url) {
String urlString = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// WIFI
urlString = url + ";interface=wifi";
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
ServiceRecord record = getWAP2ServiceRecord();
if (record != null
&& (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// WAP 2.0
urlString = url + ";deviceside=true;ConnectionUID="
+ record.getUid();
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// BES/MDS
urlString = url + ";deviceside=false";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Direct TCP/IP
urlString = url + ";deviceside=true";
} else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
// BIS
urlString = url + ";deviceside=false;ConnectionUID="
+ record.getUid();
}
}
return urlString;
}
protected static ServiceRecord getWAP2ServiceRecord() {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
for (int i = 0; i < records.length; i++) {
String cid = records[i].getCid().toLowerCase();
String uid = records[i].getUid().toLowerCase();
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
return null;
}
private class CellTower {
public String mobileCountryCode;
public int locationAreaCode;
public int signalStrength;
public int cellID;
public int age;
public int mobileNetworkCode;
private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
mobileCountryCode = mcc;
locationAreaCode = lac;
signalStrength = ss;
cellID = ci;
age = a;
mobileNetworkCode = mnc;
}
}
}
Ideally you should be using multiple fix methods (your Criteria) to gather GPS information. Using just the default will not work in all circumstances, so you need to have fallback options. Here are the Criteria, in preferred order, that I use in the States and seems to do well. You just have to loop through them until you have a set that works.
//Speed optimal
BlackBerryCriteria speed = new BlackBerryCriteria();
speed.setHorizontalAccuracy(50);
speed.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
speed.setCostAllowed(true);
speed.setPreferredResponseTime(10000);
//MS-Based
BlackBerryCriteria msBased = new BlackBerryCriteria();
msBased.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
msBased.setHorizontalAccuracy(50);
msBased.setVerticalAccuracy(50);
msBased.setCostAllowed(true);
msBased.setPreferredResponseTime(10000);
//Assisted mode
BlackBerryCriteria assisted = new BlackBerryCriteria();
assisted.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_HIGH);
assisted.setHorizontalAccuracy(50);
assisted.setVerticalAccuracy(50);
assisted.setCostAllowed(true);
assisted.setPreferredResponseTime(10000);
//Autonomous
BlackBerryCriteria autonomous = new BlackBerryCriteria();
autonomous.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
autonomous.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setCostAllowed(true);
autonomous.setPreferredResponseTime(180000);
//Cell site
BlackBerryCriteria cell = new BlackBerryCriteria();
cell.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_LOW);
cell.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setCostAllowed(true);
cell.setPreferredResponseTime(180000);

Reverse Geocoding using Blackberry 5.0 API example anyone?

So the blackberry documentation shows you the following code example:
import net.rim.device.api.lbs.*;
import javax.microedition.location.*;
public class myReverseGeocode
{
private Thread reverseGeocode;
public myReverseGeocode()
{
reverseGeocode = new Thread(thread);
reverseGeocode.setPriority(Thread.MIN_PRIORITY);
reverseGeocode.start();
}
Runnable thread = new Runnable()
{
public void run()
{
AddressInfo addrInfo = null;
int latitude = (int)(45.423488 * 100000);
int longitude = (int)(-80.32480 * 100000);
try
{
Landmark[] results = Locator.reverseGeocode
(latitude, longitude, Locator.ADDRESS );
if ( results != null && results.length > 0 )
addrInfo = results[0].getAddressInfo();
}
catch ( LocatorException lex )
{
}
}
};
}
How do I use the above mentioned code to pass in dynamic longitude/latitude values in my main application?
Is this just a basic java question? You have to use the 'final' keyword, so that the values can be passed in to the anonymous class held by the local variable 'thread'
public myReverseGeocode(final double latArg, final double lonArg)
{
Runnable thread = new Runnable()
{
public void run()
{
AddressInfo addrInfo = null;
int latitude = (int)(latArg * 100000);
int longitude = (int)(lonArg * 100000);
try
{
Landmark[] results = Locator.reverseGeocode
(latitude, longitude, Locator.ADDRESS );
if ( results != null && results.length > 0 )
addrInfo = results[0].getAddressInfo();
}
catch ( LocatorException lex )
{
}
}
};
reverseGeocode = new Thread(thread);
reverseGeocode.setPriority(Thread.MIN_PRIORITY);
reverseGeocode.start();
}

2nd Line is not getting displayed in the ListField (text wrapping is not happening) ... please advice

Here is the sample code:
class MailBoxSampleListField extends MainScreen implements FolderListener, StoreListener {
private static final int COLUMN_WIDTH_STATUS = 10;
private static final int COLUMN_WIDTH_DATE = 150;
private static final int COLUMN_WIDTH_NAME = 150;
public ListField myList;
private ListCallback myCallback;
public Vector sampleList = new Vector();
public Vector sampleVector;
private class ListCallback implements ListFieldCallback {
public Vector myVector = new Vector();
public Bitmap LIST_IMAGE = Bitmap.getBitmapResource("New.PNG");
public void drawListRow (ListField list, Graphics g, int index, int y,int w) {
displayList(g,0,y,w,(( Message )myVector.elementAt( index )), LIST_IMAGE); // for drawing the list row
for( int ii = 0; ii < sampleVector.size(); ii++) {
String text = ( String )sampleVector.elementAt(ii);
int liney = y + ( ii * list.getFont().getHeight() );
g.drawText( text, LIST_IMAGE.getWidth() + 5, liney, Graphics.ELLIPSIS, w );
}
}
public Object get( ListField list, int index ) {
return myVector.elementAt(index);
}
public int indexOfList( ListField list,String p, int s ) {
return myVector.indexOf(p,s);
}
public int getPreferredWidth ( ListField list ) {
return Graphics.getScreenWidth();
}
public void insert(Message _message, int index) {
myVector.addElement(_message);
}
public void erase () {
myVector.removeAllElements();
}
}
MailBoxSampleListField() {
ListCallback myCallback = new ListCallback();
try {
Store store = null;
store = Session.getDefaultInstance().getStore();
store.addStoreListener( this );
// retrieve Folder object fow which we want to receive message notification
try {
Folder[] folders = store.list();
Folder[] f1 = store.findFolder( "inbox" );
Folder vinbox = f1[0];
for (int i =0; i < f1.length; i++) {
f1[i].addFolderListener( this );
}
Message[] vmessages = vinbox.getMessages();
for ( int j = 0; j < vmessages.length; ++j ) {
if(vmessages[j] != null){
sampleList.addElement( vmessages[j] );
}
}
myList = new ListField(); // initialize the ListField
for ( int k = 0; k < sampleList.size(); k++ ) {
myList.insert(k);
myCallback.insert(vmessages[k], k);
}
myList.setCallback( myCallback );
add( myList );
}
catch( Exception e ){
}
}
catch ( Exception se ) {
}
}
public void displayList( Graphics g, int x, int y, int width, Message _message, Bitmap LIST_IMAGE ) {
g.drawBitmap(0, y, LIST_IMAGE.getWidth(), LIST_IMAGE.getHeight(), LIST_IMAGE, 0, 0);
sampleVector = new Vector();
Date d = _message.getReceivedDate();
Calendar c = Calendar.getInstance();
c.setTime(d);
StringBuffer sb = new StringBuffer();
sb.append( c.get( Calendar.MONTH ) );
sb.append('-');
int digit = c.get( Calendar.DAY_OF_MONTH );
if ( digit < 10 ) sb.append(0);
sb.append( digit );
sb.append(' ');
sb.append( c.get( Calendar.HOUR_OF_DAY ) );
sb.append(':');
digit = c.get( Calendar.MINUTE );
if ( digit < 10 ) sb.append( 0 );
sb.append( digit );
sb.append( ' ');
x += LIST_IMAGE.getWidth()+5;
x += COLUMN_WIDTH_DATE;
try {
String name = "<noname>";
if ( _message.isInbound() ) {
Address a = _message.getFrom();
if ( a != null )
{
name = a.getName();
if ( name == null || name.length() == 0 ) name = a.getAddr();
}
}
else
{
//get the first Recipient address
Address[] set = _message.getRecipients(Message.RecipientType.TO);
if ( set != null && set.length > 0 )
{
name = set[0].getName();
if ( name == null || name.length() == 0 ) name = set[0].getAddr();
}
}
sampleVector.addElement(name +" " + sb.toString());
} catch (MessagingException e) {
System.err.println(e);
}
x += COLUMN_WIDTH_NAME;
int remainingColumnWidth = Graphics.getScreenWidth() - x;
//get the subject, or if that doesn't exist, the first line of the body
String textToDisplay = _message.getSubject();
if ( null == textToDisplay) //no subject! get the first line of the body if present
{
Object o = _message.getContent();
if ( o instanceof String )
{
textToDisplay = (String)o;
}
else if ( o instanceof Multipart )
{
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; ++i)
{
BodyPart p = mp.getBodyPart(i);
if ( p instanceof TextBodyPart )
{
textToDisplay = (String)p.getContent();
}
}
}
}
sampleVector.addElement(textToDisplay);
} public void messagesAdded(FolderEvent e) {} public void messagesRemoved(FolderEvent e) { } public void batchOperation( StoreEvent se) { }
}
I'm not sure what you mean, could you please post a screenshot so that we can see the problem?
I'll try to help out the best I can. In my limited experience, I have noticed that in a listfield, if you have not set the row height (with setRowHeight()) to a big enough height, graphics (including text) that overflow over the size of the row will not be displayed. Have you tried setting the row height to 2 * list.getFont().getHeight() or more?
If not all rows are displayed, then I think you've missed to call myList.setSize(myVector.size());
I'm not sure what you mean by "wrapping not happening"...
The drawListRow() will be called repeatedly (for the amount of times set by the setSize() that I've suggested above).
In your current code you iterate through the whole myVector on each drawListRow() call - this is wrong.
You must use the value y which is declare in drawListRow (ListField list, Graphics g, int index, int y,int w)
like
g.drawText( text, LIST_IMAGE.getWidth() + 5, y+liney, Graphics.ELLIPSIS, w )
I am facing this issue for long time finally i got the solution.
As Alex say, you need to implement your own wrapper class, something that looks like:
TextWrapper theWrapper = new TextWrapper();
String[] wrappedText = theWrapper.textWrap(longText, wrappingWidth , 2);
//
// now draw text line by line
//
g.drawText(wrappedText[0], x, y, DrawStyle.LEFT, width);
if (wrappedText.length > 1) {
g.drawText(wrappedText[1], x, y + textFont.getHeight(), DrawStyle.LEFT | DrawStyle.ELLIPSIS, width);
}
where
public class TextWrapper {
... // put here methods used by textWrap method
//
// textWrap splits input String in lines having width as maxWidth
//
public String[] textWrap(String s, int maxWidth, int maxLines)
{
String[] result;
... // do here the wrap job on input string s
return result;
}
}

Resources