Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a twitter user's name using Twitter 4j

I'm new to android development (and java in general). I'm building an application that requires a user to signup by logging-in to their twitter account from where their basic information is imported and saved. The information required would be birthday, name (full names), username, location, sex, etc. I'm using twitter4j to accomplish this. I've tried looking at the twitter4j documentation but being an android newbie (and java in general), the documentation is a little bit hard to understand so I seem to be unable to get it to do something other than set a status update.

This is the code in my activity:

package cc.co.localsquare.app;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;

public class ConnectTwitterActivity extends BaseActivity {

  public final static String CONSUMER_KEY = "valid key";
  public final static String CONSUMER_SECRET = "valid secret";
  public final static String CALLBACK_URL = "localsquare://ConnectTwitterActivity2";

  private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
  private OAuthProvider authProvider;

  private Twitter twitter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect_twitter);

        commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
        try {
      String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
      this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
    } catch (OAuthMessageSignerException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthNotAuthorizedException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthCommunicationException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    }
    }

    protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);

      Uri uri = intent.getData();
      if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
        String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
        try {
          authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier);

          AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
              commonHttpOAuthConsumer.getTokenSecret());

          twitter = new TwitterFactory().getInstance();
          twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

          twitter.setOAuthAccessToken(accessToken);

          // Alternate way:
          // twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
          //     new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));

          // Tweet message to be updated.
          String tweet = "Hi there, This was sent from my application - OAuth, Twitter";
          twitter.updateStatus(tweet);

        }
        catch (Exception e) {
          Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
        }
      }
    }

}

How EXACTLY can I solve my problem?

like image 730
nchima Avatar asked Jan 08 '12 01:01

nchima


3 Answers

If you have the screen name of the twitter user for whom you need to get the details, then you can use User user = twitter.showUser(screenName);.Now you can access the information about the user by using getter functions on the object user, e.g. user.getName(), user.getLocation() etc.

Remember to import the User class in Eclipse. Generally you can also do it by pressing Ctrl+Shift+O in Eclipse.

like image 58
Pulkit Goyal Avatar answered Oct 16 '22 09:10

Pulkit Goyal


Get the twitter object from the session once the login in complete. That can be used in the following way to extract the name

   Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
            long userID = twitter.getId();
            twitter4j.User newUser=twitter.showUser(twitter.getScreenName());
            String name=newUser.getName();

You can explore several methods from User class to get different attributes of user like profile image, friendlistlength etc @Vineet Bhatia

like image 39
Ajak6 Avatar answered Oct 16 '22 09:10

Ajak6


Use twitter.showUser() method to get user details. To get user's name do user.getName() Remember javadoc is your friend.

like image 40
Vineet Bhatia Avatar answered Oct 16 '22 09:10

Vineet Bhatia