Simulating the Latitudes and Longitudes in BlackBerry Simulator - blackberry

I am a newbie in Blackberry.I tried with finding the latitudes and longitudes . I used the below code, but it always returns 0.0, 0.0 for both latitude and longitudes. Can somone make sure whether i have picked up the right code.(or) am i doing wrong some where.
Even i tried with setting the latitude and longitude in the BB simulator too . (Simulate->GPS Location-> Added a new Loaction), but still getting the lat & lon as (0.0,0.0).
Please find the code that i tried with,
// Locationfinder.java
package com.beacon.bb.app;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class LocationFinder extends MainScreen {
private int _interval = -1;
private double mLatitude, mLongitude;
public LocationFinder() {
super();
// Set criteria for selecting a location provider:
Criteria cr= new Criteria();
cr.setCostAllowed(true);
cr.setPreferredResponseTime(60);
cr.setHorizontalAccuracy(5000);
cr.setVerticalAccuracy(5000);
cr.setAltitudeRequired(true);
cr.isSpeedAndCourseRequired();
cr.isAddressInfoRequired();
add(new RichTextField("Getting Coordinates...."));
try{
LocationProvider lp = LocationProvider.getInstance(cr);
if( lp!=null ){
lp.setLocationListener(new LocationListenerImpl(), _interval, 1, 1);
}
add(new RichTextField("Calulating GPS Cordinates :"));
add(new RichTextField("Latitude :" + mLatitude + "," + "Longitude :" + mLongitude));
//System.out.println("Lon" + longitude + " Lat "+ latitude + " course "+course+" speed "+speed+" timestamp "+timestamp);
}
catch(LocationException le)
{
add(new RichTextField("Location exception "+le));
}
}
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if(location.isValid()) {
double longitude = location.getQualifiedCoordinates().getLongitude();
double latitude = location.getQualifiedCoordinates().getLatitude();
double altitude = location.getQualifiedCoordinates().getAltitude();
float speed = location.getSpeed();
System.out.println("Lon" + longitude + " Lat "+ latitude + " speed "+speed);
mLatitude = latitude;
mLongitude = longitude;
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
// MUST implement this. Should probably do something use ful with it as well.
}
}
}

u have set the _interval to -1 which should be a valid time in seconds. i means _interval value indicates after how much time the location will be listened.
also try this link:
Current latitude and longitude in a BlackBerry app

Related

Twitter4j Search API , tweets based on location and time Interval

I have a specific requirement that i want to collect all the tweets according to the following parameters
1) Im using search API , for example i want to search for "Iphone6"
2) Region wise , ie if i specify the latitude and longitude as per city I get the results, is it possible to fetch all the results country wise( as in the code when i specity the latitude and longitude of india
it doesnt work !)
3) At what intervals should I run my application , so that I get the newly updated tweets , without getting the previously fetched tweets.
This is the code that I have written
public final class twitterdate {
public static void main(String[] args)throws Exception {
double res;
double lat,lon;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("MyKEY")
.setOAuthConsumerSecret("MySecret")
.setOAuthAccessToken("MyAccesstoken")
.setOAuthAccessTokenSecret("MyTokenSecret").setHttpConnectionTimeout(100000);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
lat=18.9750; // THis works , but it doenst work when I specify latitude and longitude of India
lon=72.8258;
res=1;
try {
QueryResult result=twitter.search(new Query("iphone").since("2014-11-19").until("2014-11-22").geoCode(new GeoLocation(lat, lon), res,"1mi"));
// Since and untill doesnt work as expected sometimes it fetches the date tweets specified on "since" method sometimes fetches the tweets specified on the date of until method
// Also since and until doesnt work when i specify a time stamp.
List<Status> qrTweets = result.getTweets();
System.out.println("hi");
for (Status tweet : qrTweets )
{
System.out.println( tweet.getId() + " " + "#" + tweet.getUser().getScreenName() + " : " + tweet.getText() + " :::" + tweet.getCreatedAt() );
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I would be greatful if somebody can help me with the requirement that I have as I have googled a lot but couldnt find any proper solution.
Thanks in advance !
Have you tried using FilterQuery? The code snippet below would give you a continuous stream of tweets.
As per my understanding you want to fetch tweets from India with content related to iphone6.
With Search query you may end up getting same set of tweets over and again.
You can try something like this below, I am not sure what co-ordinates you have used to fetch tweets from India !, you have to do some trial and error and fine tune the co-ordinates you want to locate your tweets around.
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
//if (status.getText().contains)
if(status.getUser().getLang().equalsIgnoreCase("en")
|| status.getUser().getLang().equalsIgnoreCase("en_US")) {
System.out.println(status.getUser().getName() + " :: " + status.getText() + " :: " + status.getGeoLocation());
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
public void onException(Exception ex) {
ex.printStackTrace();
}
public void onScrubGeo(long arg0, long arg1) {
}
public void onStallWarning(StallWarning arg0) {
}
};
ConfigurationBuilder config = new ConfigurationBuilder();
config.setOAuthConsumerKey("");
config.setOAuthConsumerSecret("");
config.setOAuthAccessToken("");
config.setOAuthAccessTokenSecret("");
TwitterStream twitterStream = new TwitterStreamFactory(config.build()).getInstance();
twitterStream.addListener(listener);
FilterQuery query = new FilterQuery();
// New Delhi India
double lat = 28.6;
double lon = 77.2;
double lon1 = lon - .5;
double lon2 = lon + .5;
double lat1 = lat - .5;
double lat2 = lat + .5;
double box[][] = {{lon1, lat1}, {lon2, lat2}};
query.locations(box);
String[] trackArray = {"iphone"};
query.track(trackArray);
twitterStream.filter(query);
There is however one caveat with FilterQuery that it uses location OR trackList for fetching data. To counter this may be you can put a content filter logic in onStatus() method.
Hope this helps you.

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
}

Current latitude and longitude in a BlackBerry app

I want to get the user's latitude and longitude in my BlackBerry app, and then generate the maps according to it.
How can I do that?
my code is:
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;
import net.rim.device.api.system.Application;
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 double longitude, latitude;
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);
}
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);
}
}
}
}
}
A Google result (coincidentally Stack Overflow) reveals the API call getLocation(). This may provide you with a starting point for retrieving the longitude and latitude.
Addition; the following may be helpful (from a subsequent Google search using terms based on your comment): http://www.blackberryforums.com/developer-forum/133152-location-api.html. I would quote some of the code, but there is a fair bit of information there. Let's just hope the link remained valid, or you post your solution when found :)

Blackberry - change latitude and longitude on the device to test app

I want to test my app on the device. Is it possible to hard code the latitude and longitude values somewhere in the device settings so the app reads those instead of the current location?
I want to test my app for different locations other than my current location.
In the BB simulator you can go to Simulate > GPS Location. Click the Add button and enter in a name, latitude and longitude. Click save and the simulator will start feeding your new location to the apps. Note that whatever location is displayed in the drop down is the one that will be reported by the simulator.
Inside GPS mockup
If you have access to your application code, you can always create a mockup implementation for LocationProvider so it will read location and speed data from file or RecordStore and return it as a Location, something like
public class MockupLocationProvider extends LocationProvider {
public MockupLocationProvider() {
//prepare a file or RecordStore with locations here
}
public Location getLocation(int arg0) throws LocationException,
InterruptedException {
//read data from file or RecordStore
double latitude = 321;
double longitude = 34;
float altitude = 21;
//create and return location
Location result = new GPSLocation(latitude,
longitude, altitude);
return result;
}
public int getState() {
// mockup location provider always available
return LocationProvider.AVAILABLE;
}
public void reset() {
// your code
}
public void setLocationListener(LocationListener listener,
int interval, int timeout, int maxAge) {
// your code
}
}
and mockup for your Location
public class GPSLocation extends Location {
double _latitude, _longitude;
float _altitude, _horAcc = 0, _verAcc = 0, _speed;
public GPSLocation(double lat, double lon, float alt) {
init(lat, lon, alt);
}
public GPSLocation(double lat, double lon, float alt, float spd) {
init(lat, lon, alt);
_speed = spd;
}
private void init(double lat, double lon, float alt) {
_latitude = lat;
_longitude = lon;
_altitude = alt;
}
public QualifiedCoordinates getQualifiedCoordinates() {
QualifiedCoordinates c = new QualifiedCoordinates(_latitude,
_longitude, _altitude, _horAcc, _verAcc);
return c;
}
public float getSpeed() {
return _speed;
}
public String toString() {
String result = "Lat:" + String.valueOf(_latitude) + "|Lon:"
+ String.valueOf(_longitude) + "|Alt:"
+ String.valueOf(_altitude);
return result;
}
}
Then somewhere on the screen
MockupLocationProvider gpsProvider = new MockupLocationProvider();
GPSLocation loc = (GPSLocation)gpsProvider.getLocation(0);
add(new RichTextField(loc.toString()));
Outside GPS mockup
Another option is to generally mockup GPS signals.
Steps are:
configure device gps receiver for
bluetooth (for ex.)
setup some
opensource gps server on your desktop
to produce location data over
bluetooth
change configuration/code
of gps server to mockup location data
Other options
There is a possibility to uncontrolled change of location gps data by shielding gps receiver with some radio-material (like alluminium foil or so) :)

How to show our own icon in BlackBerry Map?

I want to know how to use our own logo to show the particular place in BBMap? Can anyone knows how to do this ?
BlackBerry Map
It's not possible in Blackberry Map to show custom icon for POI.
Things you can include in Location on Blackberry Map:
The latitude of the location * 100,000. South is negative.
The longitude of the location * 100,000. West is negative.
The label to be displayed beside the location.
The description displayed when the BlackBerry smartphone user selects
details.
Zoom level from 0 to MAX_ZOOM.
Address
City
Province or state
Country
Postal code
Phone
Fax
URL
Email address
Category
Rating information between 0 and 5
See What Is - BlackBerry Maps Location Document Format
Also see How To - Invoke BlackBerry Maps
Using MapField
As an alternative you can try MapField + manager/screen paint override.
Custom extension for MapField:
class CustomMapField extends MapField {
Bitmap mIcon;
XYRect mDest;
public void moveTo(Coordinates coordinates) {
super.moveTo(coordinates);
mDest = null;
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (null != mIcon) {
if (null == mDest) {
XYPoint fieldOut = new XYPoint();
convertWorldToField(getCoordinates(), fieldOut);
int imgW = mIcon.getWidth();
int imgH = mIcon.getHeight();
mDest = new XYRect(fieldOut.x - imgW / 2,
fieldOut.y - imgH, imgW, imgH);
}
graphics.drawBitmap(mDest, mIcon, 0, 0);
}
}
}
Example of use:
class Scr extends MainScreen {
CustomMapField mMapField;
Coordinates mCoordinates;
public Scr() {
LocationProvider provider = null;
Location location = null;
try {
provider = LocationProvider.getInstance(null);
} catch (LocationException e) {
e.printStackTrace();
}
try {
location = provider.getLocation(-1);
} catch (LocationException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
mCoordinates = location.getQualifiedCoordinates();
add(new LabelField("Latitude: "
+ String.valueOf(Coordinates.convert(
mCoordinates.getLatitude(),
Coordinates.DD_MM_SS))));
add(new LabelField("Longitude: "
+ String.valueOf(Coordinates.convert(
mCoordinates.getLongitude(),
Coordinates.DD_MM_SS))));
mMapField = new CustomMapField();
mMapField.mIcon = Bitmap.getBitmapResource("poi_icon.png");
mMapField.moveTo(mCoordinates);
add(mMapField);
}
}
See also
Using MapComponent in Blackberry
GPS and BlackBerry Maps Development Guide
Prepare GPS data
If it's real device, be sure GPS is available and turned on.
If it's simulator, then before you start program use simulator menu -> simulate -> GPS Location to set GPS data.
Other option is hardcode your own Coordinats and use them without GPS:
double latitude = 51.507778;
double longitude = -0.128056;
Coordinates mCoordinates = new Coordinates(latitude, longitude, 0);

Resources