URL Read CodeName One - url

I'm relatively new to Codename One. I'm trying to read an URL and save the content on a String. I tried:
private String lectura = "";
private String escritura = "";
/*-------------------------------------------------------
* Methods
*-------------------------------------------------------
*/
public Bulbs(int i, char rtype){
type = rtype;
number = i;
status = readCNO(type, number);
}
public String giveStatus(){
status = readCNO(type, number);
return status;
}
public void turnBulbOn(){
writeCNO('B', number, 1);
}
public void turnBulbOff(){
writeCNO('B', number, 0);
}
public String readCNO(char type, int number){
ConnectionRequest r = new ConnectionRequest();
r.setUrl("http://192.168.1.3/arduino/R!" + type + "/" + Integer.toString(number));
r.setPost(false);
r.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
lectura = decodedData;
} catch (Exception ex)
{
ex.printStackTrace();
lectura = "NoBulb";
}
}
});
NetworkManager.getInstance().addToQueue(r);
return lectura;
}
public String writeCNO(char type, int number, int action){
ConnectionRequest r2 = new ConnectionRequest();
r2.setUrl("http://192.168.1.3/arduino/R!" + type + "/" + Integer.toString(number) + "/"+ action);
r2.setPost(false);
r2.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
escritura = decodedData;
} catch (Exception ex)
{
ex.printStackTrace();
escritura = "NoBulb";
}
}
});
NetworkManager.getInstance().addToQueue(r2);
return escritura;
}
However when I run it, the Console displays a bunch of errors like:
Duplicate entry in the queue: com.codename1.io.ConnectionRequest: com.codename1.io.ConnectionRequest#22b3c488
Help very appreciated!
David.

You are adding the exact same URL to the queue twice which Codename One detects as a probable mistake. If this is intentional just invoke setDuplicateSupported(true) on both connection requests.

Related

Sentiment Analysis with OpenNLP

I found this description of implementing a Sentiment Analysis task with OpenNLP. In my case I am using the newest OPenNLP-version, i.e., version 1.8.0. In the following example, they use a Maximum Entropy Model. I am using the same input.txt (tweets.txt)
http://technobium.com/sentiment-analysis-using-opennlp-document-categorizer/
public class StartSentiment {
public static DoccatModel model = null;
public static String[] analyzedTexts = {"I hate Mondays!"/*, "Electricity outage, this is a nightmare"/*, "I love it"*/};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);
}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("bin/text.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "2");
tp.put(TrainingParameters.ITERATIONS_PARAM, "30");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text){
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(new String[]{text});
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
}
In my case no matter what input String I am using, I am only getting a positive estimation of the input string. Any idea what could be the reason?
Thanks

Blackberry push notifiaction message showing in pop up screen

have used this link for push notification http://rincethomas.blogspot.in/2012/07/push-notification-in-blackberry.html
the code is running fine and i'm receiving push notification in dialog, but instead of showing the default dialog, i have created my own pop up screen to show push message
but i am getting error in my PushMessageReader.java as you can check that in link. here is my PushMessageReader.java code for pop up screen to show push message
public final class PushMessageReader {
// HTTP header property that carries unique push message ID
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
// content type constant for text messages
private static final String MESSAGE_TYPE_TEXT = "text";
// content type constant for image messages
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
static Popupscreen popup;
private static String text;
/**
* Utility classes should have a private constructor.
*/
private PushMessageReader() {
popup = new Popupscreen();
}
/**
* Reads the incoming push message from the given streams in the current thread and notifies controller to display the information.
*
* #param pis
* the pis
* #param conn
* the conn
*/
public static void process(PushInputStream pis, Connection conn) {
System.out.println("Reading incoming push message ...");
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException("Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
System.out.println("Message props: ID=" + msgId + ", Type=" + msgType + ", Encoding=" + encoding);
boolean accept = true;
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType == null) {
System.out.println("Message content type is NULL");
accept = false;
} else if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
// a string
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
PushMessage message = new PushMessage(msgId, System.currentTimeMillis(), binaryData, true, true );
text = new String( message.getData(), "UTF-8" );
System.out.println("PUSH MESSAGE================ "+text);
try{
/*final Dialog screen = new Dialog(Dialog.D_OK_CANCEL, " "+text,Dialog.OK,
//mImageGreen.getBitmap(),
null, Manager.VERTICAL_SCROLL);*/
final UiEngine ui = Ui.getUiEngine();
Application.getApplication().invokeAndWait(new Runnable() {
public void run() {
NotificationsManager.triggerImmediateEvent(0x749cb23a76c66e2dL, 0, null, null);
ui.pushGlobalScreen(popup, 0, UiEngine.GLOBAL_QUEUE);
}
});
//screen.setDialogClosedListener(new MyDialogClosedListener());
}
catch (Exception e) {
// TODO: handle exception
}
// TODO report message
} else {
System.out.println("Unknown message type " + msgType);
accept = false;
}
} else {
System.out.println("Received duplicate message with ID " + msgId);
}
pis.accept();
} catch (Exception e) {
System.out.println("Failed to process push message: " + e);
}
}
/**
* Check whether the message with this ID has been already received.
*
* #param id
* the id
* #return true, if successful
*/
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
// new ID, append to the history (oldest element will be eliminated)
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
class Popupscreen extends PopupScreen{
LabelField label = new LabelField("");
ButtonField Okbutn;
public Popupscreen(){
super(new VerticalFieldManager(), Screen.DEFAULT_CLOSE);
Okbutn = new ButtonField("ok",ButtonField.FIELD_HCENTER);
LabelField lbl = new LabelField("SUNRAYS", LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER){
protected void paintBackground(net.rim.device.api.ui.Graphics g)
{
g.clear();
g.getColor();
//g.setColor(Color.WHITESMOKE);
//g.fillRect(0, 0, Display.getWidth(), Display.getHeight());
g.setColor(Color.WHITESMOKE);
}
};
add(lbl);
add(label);
add(Okbutn);
label.setText(text);
Okbutn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
close();
}
});
//this.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.WHITE, 80));
// setBorder(BorderFactory.createSimpleBorder(new XYEdges(),Border.STYLE_TRANSPARENT));
}
}
}

listfield with bitmap loaded from server

i have made a listfield with images, the listfield is parsed from online xml file.
it seems that downloading the images into the listfield is blocking the process of parsing the content of the listfield "text" , i want to show the content of the listfield "text" and then start to proccess the download of the images and then show the images.
here is the code to call the downloader class:
Thread t = new Thread();
{
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
// do nothing
}
if (!fconn.exists()) {
UrlToImage bit = new UrlToImage(imageurlStrin);
pic = bit.getbitmap();
}
}catch (Exception ioe) {
System.out.println("error 18");
}
};
t.start();
and this is the downloader class code:
public class UrlToImage implements Runnable{
String imageurlStrin=null;
BitmapDowloadListener listener=null;
public static Bitmap _bmap;
private EncodedImage eih1;
public void run() {
UrlToImage bit = new UrlToImage(imageurlStrin);
}
public UrlToImage(String imageurlStrin)
{
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
//byte[] data1 = null;
try
{
connection = (HttpConnection) Connector.open(imageurlStrin, 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();
int scrhi = Display.getWidth()/4;
int scrwe = Display.getWidth()/4;
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(scrhi));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(scrwe));//width
bitmap = bitmap.scaleImage32(multW,multH);
Bitmap thefinal = bitmap.getBitmap();
//url = StringUtils.replaceAll(url ,"http://u.bbstars.com/i-", "");
final String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
String Dire = "file:///store/home/user/pictures/listfield/";
JPEGEncodedImage finalJPEG = JPEGEncodedImage.encode(thefinal, 100);
byte[] raw_media_bytes = finalJPEG.getData();
int raw_length = finalJPEG.getLength();
int raw_offset = finalJPEG.getOffset();
FileConnection filecon = null;
OutputStream out = null;
try {
filecon = (FileConnection) Connector.open(Dire,Connector.READ_WRITE);
if(!filecon.exists()){
filecon.mkdir();
}
filecon = (FileConnection) Connector.open(saveDire,Connector.READ_WRITE);
if(!filecon.exists()){
filecon.create();
}
out = filecon.openOutputStream();
out.write(raw_media_bytes, raw_offset, raw_length);
out.close();
filecon.close();
System.out.println("----------------file saved"+imageFilename);
} catch (IOException e) {
System.out.println("---------------===================- error saving the file");
};
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
InputStream input = fconn.openInputStream();
int available = input.available();
final byte[] data1=IOUtilities.streamToBytes(input);
input.read(data1, 0, available);
eih1 = EncodedImage.createEncodedImage(data1,0,data1.length);
}
}catch (Exception ioe) {
System.out.println("error gettin bitmap details from the piture");
}
_bmap=eih1.getBitmap();
}
public Bitmap getbitmap()
{
return _bmap;
}
}
what should i do to prevent UI blocking, i want the perfect why to call that downloader class without stoping the process of parsing the other listfield content?
I think you may just have a simple syntax problem with the way you declared your thread object. See the BlackBerry documentation on Thread here
When you create a Thread, you normally either extend the Thread class with a subclass of your own, that implements the run() method, or you pass a new Runnable object in to the constructor of your Thread object. In your code, you actually declare a Thread instance, and create it, but do not give it a Runnable, or override the default run() method. So, this thread won't do anything in the background.
You have essentially declared a chunk of code within a local scope. That's what happens if you just put some code within a set of curly brackets ({ and }) that are not attached to anything:
Thread t = new Thread();
// this next curly bracket starts a "local scope". it is NOT part of Thread t!
{
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
// The rest of your code here will not be executed on Thread t. It will be executed
// on the thread where you instantiate Thread t, right before you call t.start();
// If this code is called on the main/UI thread (which it probably is), then the
// network request will block the UI thread, which will stop the loading of the rest
// of the list.
};
t.start();
What you probably want is this:
Thread t = new Thread(new Runnable() {
public void run() {
String imageFilename = imageurlStrin.substring(imageurlStrin.lastIndexOf('/') + 1);
String saveDire = "file:///store/home/user/pictures/listfield/"+imageFilename;
try {
FileConnection fconn = (FileConnection)Connector.open(saveDire);
if (fconn.exists()) {
// do nothing
}
if (!fconn.exists()) {
UrlToImage bit = new UrlToImage(imageurlStrin);
pic = bit.getbitmap();
}
} catch (Exception ioe) {
System.out.println("error 18");
}
}
});
t.start();
Try that, and see if that fixes the problem.

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);

Resources