Blackberry issue on cell site GPS tracking - blackberry

In my BB app, I try to fetch the location using the cell site.
But it always throws a Location exception:
Timed out while waiting for Geolocation.m=0
Here is my code
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
LocationProvider provider = LocationProvider.getInstance(criteria);
Location location = provider.getLocation(-1);
QualifiedCoordinates qualifiedCoordinates = location.getQualifiedCoordinates();
double latitude = qualifiedCoordinates.getLatitude();
double longitude = qualifiedCoordinates.getLongitude();
But if i change the parameters to
criteria.setHorizontalAccuracy(50);
criteria.setVerticalAccuracy(50);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
the assisted GPS works fine and I will get the correct location of device.

class LocationTracker{
private LocationProvider provider;
Criteria cr;
public LocationTracker() {
cr= new Criteria();
resetGPS();
}
public void resetGPS(){
try {
provider = LocationProvider.getInstance(cr);
if(provider != null) {
provider.setLocationListener(new MyLocationListener(),60, -1, -1);
}
}
catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyLocationListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location){
if(location != null && location.isValid()){
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try {
LAT = location.getQualifiedCoordinates().getLatitude();
System.out.println("=============================lattitude :: "+LAT);
LONG= location.getQualifiedCoordinates().getLongitude();
System.out.println("==================================longitude ::"+LONG);
}
catch(Exception e){
}
}
}
public void providerStateChanged(LocationProvider provider, int newState){
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE){
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}

Like vijay, you can register to location update.
If you still want to use your solution, you have to be sure that
- It is threaded (and not just only not to get an ANR, it is a requirement)
- You have a SIM card with a Blackberry option
- You run on at least OS 5.0.0

Related

BlackBerry Refresh location via GPS or Cell Tower

I am trying to refresh the current location through a click of a button. The location can be acquired via GPS or Cell Tower, whichever is available. My problem is I never see the "Loading Screen". I know it appears as something appears/closes instantly while the coordinates remain zero. Can somebody help me - what I am doing wrong below?
Neither the location is updated nor the loading screen appears. Without the loading screen and by multiple clicks of the "refresh button" I do get the location. Below is my code for handling clicks on the "Refresh Button":
FieldChangeListener refreshImgListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
Thread backgroundWorker = new Thread(new Runnable() {
public void run() {
refreshCoordinates();
}
});
busyDialog.setEscapeEnabled(false);
busyDialog.show();
backgroundWorker.start();
}
};
And my refreshCoordinates() method is as below:
public void refreshCoordinates() {
do
{
getLatitude(handleeGPS.latitude);
getLongitude(handleeGPS.longitude);
} while ((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
lblLatitude.setText(lati);
lblLongitude.setText(longi);
busyDialog.cancel();
}
} );
}
public static String getLatitude(double value)
{
lati= Double.toString(value);
return lati;
}
public static String getLongitude(double value)
{
longi= Double.toString(value);
return longi;
}
Class that returns the latitude and longitude values:
public class handleeGPS{
static GPSThread gpsThread;
public static double latitude;
public static double longitude;
public handleeGPS(){
gpsThread = new GPSThread();
gpsThread.start();
}
private static class GPSThread extends Thread{
public void run() {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");
if(m_bbHandle>0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
} else {
try {
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
latitude = myLocation.getQualifiedCoordinates().getLatitude();
longitude = myLocation.getQualifiedCoordinates().getLongitude();
if(latitude==0.0 && longitude==0.0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();
//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();
//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
catch ( InterruptedException iex ) {
return;
}
catch ( LocationException lex ) {
return;
}
} catch ( LocationException lex ) {
return;
}
}
return;
}
}
private static void WriteDataGoogleMaps(OutputStream out, int cellID, int lac)
throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
Ok, so although my original answer was valid, the new code you posted has some different problems, so I'm posting a second answer. There were enough things that didn't look right, that I just rewrote your handleeGPS class. I'll explain the major changes I made, one-by-one:
Try to use Java naming conventions. This makes it easier for us to help you. Before you posted the code to your handleeGPS class, I thought it was a variable, because lowercase names are usually used for variables, not classes.
Avoid duplicating code. The handleeGPS class had a lot of code to read through, but most of it was the code to get location from Google's web service, which you duplicated in two places. Just make a method that contains only that code, and call it twice.
I renamed your handleeGPS class to GPSHandler. I'm not sure if handlee was an error, or if that's a word in another language that you used. Anyway, the name should at least start with an uppercase letter.
Avoid lots of static variables and methods. Sometimes, there really should be only one of something. A GPS handling class is probably a good example of that, because the device only has one GPS system. But, to enforce this code construct, don't mark everything as static. Just make the class a Singleton, which involves creating only one static member variable (_instance) and one static method (getInstance()). In my code, you will access the class like this: GPSHandler gps = GPSHandler.getInstance();.
I believe the check you had for whether BB maps was installed was actually backwards. You looked up the net_rim_bb_lbs module, and if it was greater than zero (which means BB Maps is installed) then you went directly to the Google webservice. I think you want it the other way around (try device GPS if BB Maps installed). Also, since 6.0, you need to check for net_rim_bb_maps, too.
Before you posted the update, I thought your getLatitude() and getLongitude() methods were actually fetching the device location. That was a bad assumption on my part. They were just converting numbers to strings. So, there's no reason for that to be done in the background (with a Thread). You already wrote your handleeGPS class to use a background thread, which is good. One background thread is enough. The UI that uses the location information should not also need a background Thread. I changed the code to add a GPSListener interface. That interface should be implemented by your UI code, to receive location updates. There is no reason to keep looping, asking if the location is not equal to {0.0, 0.0}. That's inefficient. With my code, you will just get notified when the location does change.
The original code was not thread safe. The handleeGPS latitude and longitude variables were set on the background thread, and accessed on the UI thread. That's not safe. Two threads should not be reading and writing the same piece of data at once. By changing the code to push location data to the GPSListener, it avoids this problem.
I uncommented the Dialog.alert() code you had inside your handleeGPS class, which would not have worked for you, because you're not allowed to make UI calls from the background. I surrounded those calls with UiApplication.getUiApplication().invokeLater() to make them safe.
To use this class, in your UI code somewhere, you would do this, instead of using a Thread to run your refreshCoordinates() method:
public void fieldChanged(Field field, int context)
// this is called when your location refresh button is clicked
GPSHandler.getInstance().setListener(this);
GPSHandler.getInstance().requestLocationUpdates();
busyDialog.setEscapeEnabled(false);
busyDialog.show();
}
...
public void onLocationReceived(Coordinates location) {
lblLatitude.setText(Double.toString(location.getLatitude()));
lblLongitude.setText(Double.toString(location.getLongitude()));
busyDialog.cancel();
}
Make sure the class where you put that code (above) also implements GPSListener, which is an interface, defined here:
public interface GPSListener {
public void onLocationReceived(Coordinates location);
}
and finally, the GPSHandler:
public class GPSHandler {
private GPSThread _gpsThread;
private Coordinates _location;
private boolean _gotLocation;
private GPSListener _listener;
/** this class will be a Singleton, as the device only has one GPS system */
private static GPSHandler _instance;
/** #return the Singleton instance of the GPSHandler */
public static GPSHandler getInstance() {
if (_instance == null) {
_instance = new GPSHandler();
}
return _instance;
}
/** not publicly accessible ... use getInstance() */
private GPSHandler() {
}
/** call this to trigger a new location fix */
public void requestLocationUpdates() {
if (_gpsThread == null || !_gpsThread.isAlive()) {
_gpsThread = new GPSThread();
_gpsThread.start();
}
}
public void setListener(GPSListener listener) {
// only supports one listener this way
_listener = listener;
}
private void setLocation(final Coordinates value) {
_location = value;
if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
_gotLocation = true;
if (_listener != null) {
// this assumes listeners are UI listeners, and want callbacks on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_listener.onLocationReceived(value);
}
});
}
}
}
private class GPSThread extends Thread {
private void getLocationFromGoogle() {
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
writeDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
final int code = dataInputStream2.readInt();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(code + "");
}
});
if (code == 0) {
final double latitude = dataInputStream2.readInt() / 1000000D;
final double longitude = dataInputStream2.readInt() / 1000000D;
setLocation(new Coordinates(latitude, longitude, 0.0f));
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(latitude+"-----"+longitude);
}
});
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private void tryGetLocationFromDevice() {
_gotLocation = false;
try {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
setLocation(myLocation.getQualifiedCoordinates());
} catch ( InterruptedException iex ) {
System.out.println(iex.getMessage());
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
if (!_gotLocation) {
getLocationFromGoogle();
}
}
public void run() {
int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); // OS < 6.0
int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0+
if (bbMapsHandle > 0 || bbMapsHandle60 > 0) {
tryGetLocationFromDevice();
} else {
getLocationFromGoogle();
}
}
}
private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
There's a lot of code that we can't see (e.g. getLatitude(), getLongitude(), refreshDetails()). So, there could be something going wrong there. Also, I don't see any Loading Screen in the code you posted, so I can't say why that isn't showing.
But, here's something that doesn't look right:
synchronized (Application.getEventLock())
{
busyDialog.show();
}
If you read this BlackBerry forum question, you'll see that trying to synchronize on the application event lock from the main (UI) thread can cause your app to freeze. The public void fieldChanged(Field field, int context) method is always called on the UI thread, because it's the UI thread that monitors buttons for clicks, and calls back your click handlers, like fieldChanged().
You can also read the BlackBerry API docs for Application, that explain that getEventLock() is for worker (also known as background) threads, not the main (aka UI) thread.
So, there's no need to use special techniques to get the event lock, in code that already runs on the UI thread. Instead of the code above, just do this:
busyDialog.show();
Both of these techniques:
synchronized (Application.getEventLock())
{
busyDialog.show();
}
or
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
busyDialog.show();
}
});
are ways to safely call UI methods from a background thread. But, you shouldn't use those in code that you know is running on the UI thread already.
Try fixing that, and see if your problem disappears.
Edit: also, your code is checking for a username and password before refreshing the location. Is that really what you want? I don't think this has anything to do with your problem, but normally, I wouldn't expect to need a username or password to access location services. Of course, I don't know your application, so this is really just a comment on my part.
I think thee is simple answer is error here:
((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));
You have to use String.equals() instead of == operator.
After first call longi and lati have "0.0" value. But == will return false because it compare references by default and they are different because it's different objects.

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. :)

How to get current location in blackberry device?

In simulator my gps code work fine. But when I install my app in device I can't get current latitude and longitude.
When I send lat long from simulator it get proper lat long which is send through simulator. I don't know why is not working in device?
I have already enable from Option > Advance option > gps > gps servce and set Location ON.
Is there any other setting for get current location in device?
private boolean currentLocation() {
boolean retval = true;
try {
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
} else {
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
} catch (LocationException e) {
System.out.println("Error: " + e.toString());
}
return retval;
}
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();
// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}
// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}
Try this code
Thread thread = new Thread(new Runnable() {
public void run() {
bCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_CELLSITE)) {
bCriteria.setMode(GPSInfo.GPS_MODE_CELLSITE);
} else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST)) {
bCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
} else if (GPSInfo
.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS)) {
bCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
} else {
bCriteria.setCostAllowed(true);
bCriteria
.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
}
try {
bProvider = (BlackBerryLocationProvider) BlackBerryLocationProvider
.getInstance(bCriteria);
if (bProvider != null) {
bProvider.setLocationListener(new handleGPSListener(),
-1, -1, -1);
try {
bLocation = (BlackBerryLocation) bProvider
.getLocation(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (LocationException lex) {
lex.printStackTrace();
return;
}
}
});
thread.start();
then implement Location Listener in the class
public class handleGPSListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
}
}

Blackberry GPS returns zero for longitude and latitude

I am using the following class to get GPS location from blackberry, but I am always getting zero longtude and latitude values. Why is that?
public class LocationTracker extends TimerTask {
private double longitude;
private double latitude;
private double altitude;
private LocationProvider lp;
public LocationTracker() {
super();
// Set criteria for selecting a location provider:
Criteria cr = new Criteria();
cr.setCostAllowed(true);
cr.setPreferredResponseTime(60);
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setAltitudeRequired(true);
cr.isSpeedAndCourseRequired();
cr.isAddressInfoRequired();
cr.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
try {
LocationProvider lp = LocationProvider.getInstance(cr);
Location location = null;
try {
location = lp.getLocation(-1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (LocationException e){
System.out.println(e.toString());
}catch(Exception e ){
System.out.println(e.toString());
}
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
if (lp != null) {
lp.reset();
lp.setLocationListener(null, -1, -1, -1);
lp = LocationProvider.getInstance(cr);
lp.setLocationListener(new MyLocationListener(), 2, -1, -1);
}
System.out.println("Lon" + longitude + " Lat "+ latitude);
} catch (LocationException le) {
System.out.println(le.toString());
}catch(Exception e ){
System.out.println(e.toString());
}
}
public void run() {
}
public double getLongitude() {
return longitude;
}
public double getLatitude() {
return latitude;
}
public double getAltitude() {
return altitude;
}
private class MyLocationListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location != null && location.isValid()) {
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try {
latitude = qc.getLatitude();
longitude = qc.getLongitude();
altitude = qc.getAltitude();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
// TODO: if provider was disabled, then disable reporting
}
}
}
Did you check gps status from settings? If it is working try to set timeout value about 300 seconds instead of -1.
The LocationProvider may return a Location object which has isValid() false. This is done to provide additional informaton via the getExtraInfo() method.

Resources