Android: Display public Twitter timeline using OAuth and Twitter4J

So I'm trying to get a list of status objects from a public Twitter timeline ( not my own Twitter timeline or anything that I have admin access to, just a public one from a local organization ) using the Twitter4J library in Android Studio, but I'm getting a little confused by the documentation. I'm running into this error: "Invalid access token format."

I did create a developers account with Twitter and got a consumer key and token, as well as an access token and secret numbers. Those values are saved in a set of private static strings for now. TWITTER_ZOO_ID is a private long with the Twitter ID number for the feed that I want to display. Here's the applicable code that I currently have:

    Twitter twitter;
    List<Status> statuses = null;
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
            .setOAuthConsumerKey( TWITTER_CONSUMER_KEY )
            .setOAuthConsumerSecret( TWITTER_CONSUMER_SECRET )
            .setOAuthAccessToken( TWITTER_AUTH_TOKEN )
            .setOAuthAccessTokenSecret( TWITTER_AUTH_TOKEN_SECRET );
    try {
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
        twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
        statuses = twitter.getUserTimeline( TWITTER_ZOO_ID );
    }
    catch( TwitterException e ) {
        Log.e( "TwitterListFragment", "Twitter Exception" );
        return;
    }

    for( Status status : statuses )
        mAdapter.add( status );

If anyone has a link to a good example for Twitter 1.1 using Twitter4J, or can provide an example of how to get those statuses, I'd really appreciate it. I'm currently using Android Studio and including Twitter4J in Gradle from MavenCentral.

Thank you!

EDIT:

Upon further reading, I've added this additional code without success:

twitter.setOAuthConsumer( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET );
AccessToken token = new AccessToken( TWITTER_AUTH_TOKEN, TWITTER_AUTH_TOKEN_SECRET );
twitter.setOAuthAccessToken( token );


ANSWERS:


If you want to get info from a public Twitter timeline, you can use Application-only Authentication, because the user doesn´t need to login, I think it fits you because you don´t use admin rights.

The application-only auth flow follows these steps:

An application encodes its consumer key and secret into a specially encoded set of credentials.

An application makes a request to the POST oauth2/token endpoint to exchange these credentials for a bearer token.

When accessing the REST API, the application uses the bearer token to authenticate.

Because twitter4j has added this feature recently, you should use the last snapshot library.

An example using it:

private ConfigurationBuilder    builder;
private Twitter                 twitter;
private TwitterFactory          factory;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.init_act_layout);

    // setup
    builder = new ConfigurationBuilder();
    builder.setUseSSL(true);
    builder.setApplicationOnlyAuthEnabled(true);
    builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
    builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);

    Configuration configuration = builder.build();
    factory = new TwitterFactory(configuration);
    ((MyApp) (MyApp.getApp())).setTFactory(factory);

    if (isNeededTwitterAuth()) {
        twitter = factory.getInstance();
            //Get the token async and save it
    }

        //Search tweets

}

/*
 * Checks if twitter access token is already saved in preferences
 * 
 * @return true if auth needed
 */
private boolean isNeededTwitterAuth() {
    SharedPreferences settings = getSharedPreferences(Constants.TWITTER_PREFERENCES, Context.MODE_PRIVATE);
    String twitterAccesToken = settings.getString("bearerAccessToken", "");
    String twitterTokenType = settings.getString("bearerTokenType", "");
    return ((twitterAccesToken.length() == 0) && (twitterTokenType.length() == 0));
}

}

To get the bearer token, do it out of Main UI thread to avoid Network exception, f.i. using AsyncTask:

@Override
    protected OAuth2Token doInBackground(Void... params) {
        OAuth2Token bearerToken = null;

        try {
            bearerToken = twitter.getOAuth2Token();
        } catch (TwitterException e) {
            e.printStackTrace();
        }
        return bearerToken;
    }

When you obtain the bearer token, save it:

SharedPreferences appSettings = getSharedPreferences(Constants.TWITTER_PREFERENCES, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = appSettings.edit();
            prefEditor.putString("bearerAccessToken", result.getAccessToken());
            prefEditor.putString("bearerTokenType", result.getTokenType());
            prefEditor.commit();

And to use the bearer token:

OAuth2Token bearerToken = new OAuth2Token(bearerTokenType, bearerAccesstoken);

        twitter.setOAuth2Token(bearerToken);

And search tweets (always out of Main thread):

@Override
 protected QueryResult doInBackground(Void... params) {

 twitter.setOAuth2Token(bearerToken);
 Query query = new Query();
 [...]
 result = twitter.search(query);

A complete explanation in the blog (in Spanish...)

And a complete example in the twitter4j github

Hope it helps!


I would recommend using the recently updated Twitter SDK (Fabric).



 MORE:


 ? Twitter OAuth Authentication Callback Returning Null - Twitter4J
 ? Twitter4j - Bad Authentication data. code - 215
 ? Tomcat fails to deploy JAX-WS webservice implementation
 ? Twitter4j HTTPClient ProxyServer and Java
 ? how to post tweet using twitter4j in java?
 ? Creating webservice (JAX-WS) with functions which return custom types
 ? saving twitter4J Status to MongoDB gives "twitter4j.Status is an interface, and JAXB can't handle interfaces"
 ? JAXB cannot handle an interface - what am I missing?
 ? Java Twitter4j addListener not defined for type twitterStream
 ? Java Twitter4j OAuth not working