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