Search code examples
javatwitter4jtype-conversion

Twitter4j: StatusListener cannot be converted to twitter4j.StreamListener


I'm trying to fetch tweets with twitter4j. I tried the sample code and I see why it doesn't work - I cannot convert the StatusListener. But I can't solve my problem either.

Does someone have an idea how to solve this?

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import java.io.IOException;

public class Home
{
    public static void main (String args[]) throws TwitterException, IOException
    {
        ConfigurationBuilder cf = new ConfigurationBuilder();
        cf.setDebugEnabled(true)
                .setOAuthConsumerKey("")
                .setOAuthConsumerSecret("")
                .setOAuthAccessToken("")
                .setOAuthAccessTokenSecret("");

        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();
            }
        };
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.addListener(listener);
        twitterStream.sample();
    }
}

Solution

  • You're missing two methods implementations in your anonymous class implementing StatusListener

    This should look like this:

    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) {}
    
        @Override
        public void onScrubGeo(long l, long l1) {}
    
        @Override
        public void onStallWarning(StallWarning stallWarning) {}
    
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };