Ok. Each time we get only 100 tweets. I want to show them on a map based on the Geolocation. Is there any way I can get 100 tweets that all of them have Geolocation. Because now only 3-4 out of 100 has Geolocation.
I read some examples with FilterQuery but Processing throws me an error on it, as unknown.
Here is an working example. This was tested using twitter4j 4.0.2
The interface StatusListener is where you can do whatever you want with your tweets Kind of... is there that they arrive
Using stream API:
import twitter4j.util.*;
import twitter4j.*;
import twitter4j.management.*;
import twitter4j.api.*;
import twitter4j.conf.*;
import twitter4j.json.*;
import twitter4j.auth.*;
TwitterStream twitterStream;
double[][] boundingBox= {
{
-180, -90
}
, {
180, 90
}
}; /// whole world;
void setup() {
size(100, 100);
background(0);
openTwitterStream();
}
void draw() {
background(0);
}
// Stream it
void openTwitterStream() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey(FILL_IN);
cb.setOAuthConsumerSecret(FILL_IN);
cb.setOAuthAccessToken(FILL_IN);
cb.setOAuthAccessTokenSecret(FILL_IN);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
twitterStream.addListener(listener);
FilterQuery filter = new FilterQuery();
filter.locations(boundingBox);
twitterStream.filter(filter);
println("connected");
}
// Implementing StatusListener interface
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
GeoLocation loc = status.getGeoLocation();
System.out.println("#" + status.getUser().getScreenName() + " - " + loc);
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
//import twitter4j.FilterQuery;
import java.util.*;
Twitter twitter;
String searchString = "shopping";
Query query;
ArrayList tweets,tweets2;
void setup()
{
frameRate(0.2);
tweets = new ArrayList();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("*");
cb.setOAuthConsumerSecret("*");
cb.setOAuthAccessToken("*");
cb.setOAuthAccessTokenSecret("*");
twitter = new TwitterFactory(cb.build()).getInstance();
query = new Query(searchString);
getNewTweets();
}
void draw()
{
try{
if (current >= tweets.size()) //if u read all the received tweets make a new query
{
tweets.clear();
tweets2.clear();
getNewTweets();
current = 0;
}
Status currentTweet = (Status) tweets.get(current);
GeoLocation loc = currentTweet.getGeoLocation();
User currentUser=(User) currentTweet.getUser(); //Get User info
double latitude = currentTweet.getGeoLocation().getLatitude();
double longitude = currentTweet.getGeoLocation().getLongitude();
println( "Longtitude: "+longitude);
println( "Latitude: "+latitude);
String user = currentUser.getScreenName();
String msg = currentTweet.getText();
println( "User: "+user);
println("Message: "+ msg);
}
catch (Exception te) {
println(te);
}
}
void getNewTweets()
{
try
{
// FilterQuery filtro = new FilterQuery();
/* filtro.locations(boundingBox);
twitter.addListener(listener);
twitter.filter(filtro);
*/
query.setCount(100); //sets the number of tweets to return per page
QueryResult result = twitter.search(query);
tweets2 = (ArrayList) result.getTweets();
for (int i = 0; i < tweets2.size(); i++) {
Status currentTweet = (Status) tweets2.get(i);
GeoLocation loc = currentTweet.getGeoLocation();
if(loc!=null){ //add to list only tweets with geo location
tweets.add(tweets2.get(i));
}
}
}
catch (TwitterException te)
{
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
Not an answer but a Simple workaround:
I know most of people don't have GPS enabled when they tweet and others would not like to share their location!
But they are still sharing their location!! Guess how? On their profiles! Their hometown, their country is mostly visible, which can give you an approximate location of where the tweet came from! You can query for the user's profile and thus his/her location using the Rest API
twitter.showUser(userScreenName).getLocation();
I think if you setGeocode before u search,then the majority of result will has Geolocation(up to 90%). but i dont know why not whole of result with geolocation. maybe it will a little helpful?
GeoLocation obj = new GeoLocation(35.8007019, -97.3383211);
query.setGeoCode(obj, 2000, Unit.valueOf("km"));
result = twitter.search(query);
Related
I'm trying to use the twitter4j API to get the stream of tweets on a specific topic.
This is my code:
TwitterStream twitterStream = inizialize();
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
System.out.println(status.getUser().getName() + " ====> " + status.getText());
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
public void onException(Exception ex) {
ex.printStackTrace();
}
#Override
public void onScrubGeo(long userId, long upToStatusId) {
// TODO Auto-generated method stub
}
#Override
public void onStallWarning(StallWarning warning) {
// TODO Auto-generated method stub
}
};
FilterQuery filterQuery = new FilterQuery("GAME");
twitterStream.addListener(listener);
twitterStream.filter(filterQuery);
twitterStream.sample(); // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
}
The stream of tweets works well, but I cannot set any query. So, I wonder, is it possible to do what I'm trying to?
Of course, the inizialize() returns a twitterStream configured with a valid oauth token.
You'll want to manually filter statuses coming from the stream. For example, if you want to show tweets that contains 'vanilla' only then you could approach like this in your onStatus:
public void onStatus(Status status) {
String statusText = status.getText();
if (statusText.toLowerCase().contains("vanilla")) {
System.out.println(status.getUser().getName() + " ====> " + statusText);
}
}
// Expecting a String[] of topics to track:
filterQuery.track(keywords);
// Within a bounding box of geo-coordinates:
filterQuery.locations(new double[][] {{lng1, lat1}, {lng2, lat2}});
// Specifies a language to track:
filterQuery.language("en");
// Number of previous statuses to stream before transitioning to the live stream:
filterQuery.count(10);
Good day
me and my team are new to coding languages, we are trying through multiple methods to make an arduino based indicator that shows which keyword out of two is more mentioned during the last 5 minutes on twitter
we tried using adafruit + IFTTT and we managed to have a stream of real time tweets of two hashtags but we are trying to find a way to collect that info and make a code that compare the total number of both hashtags and send command to arduino to spine the servo motor based on the result.
and then we tried to do it through processing language and we found this code that makes displays related hashtag tweets on screen but we couldn't make it search for two words and compare the numbers and then send signal to arduino :
//http://codasign.com/tutorials/processing-and-twitter
import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import java.util.*;
Twitter twitter;
String searchString = "#poznan";
List<Status> tweets;
int currentTweet;
void setup()
{
size(800, 600);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
getNewTweets();
currentTweet = 1;
thread("refreshTweets");
}
void draw()
{
fill(0, 40);
rect(0, 0, width, height);
currentTweet = currentTweet + 1;
if (currentTweet >= tweets.size())
{
currentTweet = 0;
}
Status status = tweets.get(currentTweet);
fill(200);
text(status.getText(), random(width), random(height), 300, 200);
delay(250);
}
void getNewTweets()
{
try
{
Query query = new Query(searchString);
//query.setSince("2016-03-17");
//query.setCount(100);
query.setResultType(Query.RECENT);
QueryResult result = twitter.search(query);
tweets = result.getTweets();
println(tweets.size());
}
catch (TwitterException te)
{
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
void refreshTweets()
{
while (true)
{
getNewTweets();
println("Updated Tweets");
delay(60000);
}
}
We are looking for alternative codes and methods to make our concept work
we are open to suggestions, don't hesitate to write to us.
You should probably split this problem in smaller ones.
A. How do I connect to Twitter and "listen" to two hashtags, counting them and comparing them.
B. How do I use arduino to move a servo according to some arbitary number in a specific range.
C. How do I communicate a number between Arduino and processing, via desired channel (wi-fi? bluetooth? usb?)
Of course this can be break even further, and perhaps it should.
Doing like this is going to be much easier to develop and debug your code. Once you got all that figured out, start to combine them.
For B and C I can help very little, it's been sometime since I last touched my Arduino. But those are not really hard to be done. In the Processing forum you can find a lot of answers about serial communication with Arduino. The search of the forum is not so good. But you can always use Google. Something like: serial arduino site:processing.org will do the search in all forums (this is like the third version) and give you easier to navigate results.
For A, I'd suggest you try a "stream" from Twitter's streamingAPI. Once you start getting results, just add them to different Lists, like
hashtag1 and hashtag2.
The size of each list is what you are looking for (if I get this right)
hashtag1.size() - hashtag2.size() will give you the "balance" between them.
edit: If, you are not going to need those status you can just add to two ints... (h1++, h2++), and forget the lists.
Here some stream sample code to get you started:
import twitter4j.util.*;
import twitter4j.*;
import twitter4j.management.*;
import twitter4j.api.*;
import twitter4j.conf.*;
import twitter4j.json.*;
import twitter4j.auth.*;
TwitterStream twitterStream;
// if you enter keywords here it will filter, otherwise it will sample
String keywords[] = {
//all you need is...
"love"
};
void setup() {
size(100, 100);
background(0);
openTwitterStream();
}
void draw() {
background(0);
}
// Stream it
void openTwitterStream() {
ConfigurationBuilder cb = new ConfigurationBuilder();
//fill oAuth data below
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
cb.setDebugEnabled(true);
cb.setJSONStoreEnabled(true);
twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
FilterQuery filtered = new FilterQuery();
filtered.track(keywords);
twitterStream.addListener(listener);
if (keywords.length==0) {
// sample() method internally creates a thread which manipulates TwitterStream
// and calls these adequate listener methods continuously. With a sample of the fireRose
twitterStream.sample();
} else {
twitterStream.filter(filtered);
}
println("connecting...");
}
// Implementing StatusListener interface
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
My goal is to collect all tweets containing the words "France" and "Germany" and to also collect associated metadata (e.g., the geo coordinates attached to the tweet). I know that this metadata is available, but I can't figure out how to access it with the Java library I'm using : "twitter4j".
Ok, so what I have so far is taken from code samples on the twitter4j site. It prints out all tweets containing my chosen keywords, as they are provided in real-time by Twitter's Streaming API. I call the filter method on my TwitterStream object, and this provides the stream. But I need more control. Namely, I would like to be able to:
1) write the tweets to a file;
2) only print out the first 1000 tweets;
3) access other metadata attached to the tweet (the filter method just prints out the username and the tweet itself).
Here is the code I have so far:
import twitter4j.FilterQuery;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Stream {
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("bbb");
cb.setOAuthConsumerSecret("bbb");
cb.setOAuthAccessToken("bbb");
cb.setOAuthAccessTokenSecret("bbb");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"France", "Germany"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
}
}
After looking at this with fresh eyes I realised the solution (which was pretty obvious). Editing the following part of the code:
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
allows me to access other metadata. For example, if I want to access the tweet's date, I simply need to add the following:
System.out.println(status.getCreatedAt());
The Error 401 comes when the API is trying to access some information which is unable to fetch at present. So you need to check the permission which are allowed on twitter. Change it to READ, WRITE and ... for full API access. Or there might be problem as you might be using the proxy server. Hence mention the proxy details using the following commands.
System.getProperties().put("http.proxyHost", "10.3.100.211");
System.getProperties().put("http.proxyPort", "8080");
To write tweets on file:
FileWriter file = new FileWriter(....);
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText() + " -> "+ status.getCreatedAt());
try {
file.write(status.getUser().getScreenName() + " - " + status.getText() + " -> "+ status.getCreatedAt() +"\n");
file.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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. :)
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 :)