Add Status Listener to TwitterStream - Java Social Media

Java examples for Social Media:Twitter

Description

Add Status Listener to TwitterStream

Demo Code

import twitter4j.*;
import twitter4j.auth.AccessToken;

import java.util.ArrayList;
import java.util.Arrays;

public class PrintFilterStream {
    public static void main(String[] args) throws TwitterException {
        if (args.length < 1) {
            System.exit(-1);/*from ww  w . j av a2 s.c o m*/
        }

        TwitterStream twitterStream = new TwitterStreamFactory()
                .getInstance();
        String consumerKey = "";
        String consumerSecret = "";
        String accessToken = "";
        String accessTokenSecret = "";

        twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
        twitterStream.setOAuthAccessToken(new AccessToken(accessToken,
                accessTokenSecret));

        twitterStream.addListener(new MyStatusAdapter());
        ArrayList<String> track = new ArrayList<String>();
        track.addAll(Arrays.asList(args[0].split(",")));
        String[] trackArray = track.toArray(new String[track.size()]);
        twitterStream.filter(new FilterQuery(0, null, trackArray));
    }
}

class MyStatusAdapter extends StatusAdapter {
    public void onStatus(Status status) {
        System.out.println("@" + status.getUser().getScreenName() + " - "
                + status.getText());
    }
}

Related Tutorials