@Override protected FetchUserTaskOutput doInBackground(FetchUserTaskInput... inputArray) { TwitterUser result = null; FetchUserTaskInput input = inputArray[0]; if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchUserTaskOutput( new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null); } String errorDescription = null; Twitter twitter = getTwitterInstance(); if (twitter != null) { try { User user = null; if (input.mVerifyCredentials != null && input.mVerifyCredentials.booleanValue()) { Log.d("api-call", "verifyCredentials"); user = twitter.verifyCredentials(); } else { Log.d("api-call", "showUser"); if (input.mUserId != null) { user = twitter.showUser(input.mUserId); } else if (input.mScreenName != null) { user = twitter.showUser(input.mScreenName); } } result = new TwitterUser(user); setUser(result); } catch (TwitterException e) { e.printStackTrace(); errorDescription = e.getErrorMessage(); Log.e("api-call", errorDescription, e); if (e.getRateLimitStatus() != null && e.getRateLimitStatus().getRemaining() <= 0) { errorDescription += "\nTry again in " + e.getRateLimitStatus().getSecondsUntilReset() + " " + "seconds"; } } } else { AppdotnetApi api = getAppdotnetApi(); if (api != null && input.mUserId != null) { result = api.getAdnUser(input.mUserId); setUser(result); } } return new FetchUserTaskOutput( new TwitterFetchResult(errorDescription == null, errorDescription), input.mCallbackHandle, result); }
@RequestMapping(value = "/{username}/accountInfo", method = RequestMethod.GET) public ResponseEntity<TwitterAccountInfo> getAccountInfo(@PathVariable String username) { TwitterAccountInfo twitterAccountInfo = new TwitterAccountInfo(); TwitterCredentials twitterCredentials = twitterCredentialsService.getTwitterCredentialsForUsername(username); Twitter twitter = TwitterAppFactory.getTwitterInstance(); AccessToken accessTokenObj = new AccessToken( twitterCredentials.getAccessToken(), twitterCredentials.getAccessTokenSecret()); twitter.setOAuthAccessToken(accessTokenObj); try { String twitterScreenName = twitter.getScreenName(); User twitterUser = twitter.showUser(twitterScreenName); twitterAccountInfo.setUsername(twitterScreenName); twitterAccountInfo.setFullName(twitterUser.getName()); twitterAccountInfo.setProfileImageUrl(twitterUser.getProfileImageURL()); twitterAccountInfo.setFollowersCount(twitterUser.getFollowersCount()); twitterAccountInfo.setFriendsCount(twitterUser.getFriendsCount()); } catch (Exception e) { LOG.warn(e.getMessage()); return new ResponseEntity<TwitterAccountInfo>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<TwitterAccountInfo>(twitterAccountInfo, HttpStatus.OK); }
public User getUser(String name) { try { return new TwitterUser(twitter.showUser(name)); } catch (TwitterException e) { e.printStackTrace(); return null; } }
private void getTweetsFromTwitter() { try { ConfigurationBuilder confbuilder = new ConfigurationBuilder(); confbuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); confbuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); btnLogoutTwitter.setVisibility(View.GONE); btnGetTweets.setVisibility(View.GONE); lblUserName.setVisibility(View.GONE); btnShowOnMap.setVisibility(View.GONE); btnUsers.setVisibility(View.GONE); Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance(accessToken); List<Status> statuses = twitter.getUserTimeline(USER_ID, new Paging(1, 10)); IDs following = twitter.getFriendsIDs(USER_ID); long[] followingList = following.getIDs(); for (int i = 0; i < followingList.length; i++) { Toast.makeText(getApplicationContext(), twitter.showUser(followingList[i]).toString(), 100) .show(); } int count = 0; // Collections.reverse(statuses); // reverse order ArrayList<String> arrayList = new ArrayList<String>(); for (Status status : statuses) { String tweettext = status.getUser().getName() + ":" + status.getText() + "\n (" + status.getCreatedAt().toLocaleString() + ")" + status.getGeoLocation(); arrayList.add(tweettext); // now single tweet is in tweettext } ListView lv = (ListView) findViewById(R.id.storeTweet); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); lv.setAdapter(arrayAdapter); } catch (Exception ex) { // failed to fetch tweet } }
@SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* initializing twitter parameters from string.xml */ initTwitterConfigs(); /* Enabling strict mode */ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); /* Setting activity layout file */ setContentView(R.layout.activity_main); loginLayout = (RelativeLayout) findViewById(R.id.login_layout); /* register button click listeners */ findViewById(R.id.btn_login).setOnClickListener(this); /* Check if required twitter keys are set */ if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) { Toast.makeText(this, "Twitter key and secret not configured", Toast.LENGTH_SHORT).show(); return; } /* Initialize application preferences */ mSharedPreferences = getSharedPreferences(PREF_NAME, 0); boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); /* if already logged in, then hide login layout and show share layout */ if (isLoggedIn) { Intent intent = new Intent(MainActivity.this, MenuActivity.class); startActivity(intent); } else { loginLayout.setVisibility(View.VISIBLE); Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(callbackUrl)) { String verifier = uri.getQueryParameter(oAuthVerifier); try { /* Getting oAuth authentication token */ AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); /* Getting user id form access token */ long userID = accessToken.getUserId(); final User user = twitter.showUser(userID); final String username = user.getName(); /* save updated token */ saveTwitterInfo(accessToken); // loginLayout.setVisibility(View.GONE); } catch (Exception e) { Log.e("Failed login Twitter!!", e.getMessage()); } } } }
private static void getTwitterProfileInfo(AccessToken accessToken2) { try { String token = accessToken2.getToken(); Log.i(TAG, "token is " + token); mUserInfo.setExtra(token); long userId = accessToken2.getUserId(); mUserInfo.setTwitterId(String.valueOf(userId)); userObj = twitter.showUser(userId); mUserInfo.setProfilePic(userObj.getBiggerProfileImageURLHttps()); long cursor = -1; IDs freinds = twitter.getFriendsIDs(userObj.getId(), cursor); Log.d(TAG, "IDS:" + freinds.getIDs()); if (freinds.getIDs() != null) { StringBuilder builder = new StringBuilder(); builder.append(""); do { for (long i : freinds.getIDs()) { builder.append(i + ","); } } while (freinds.hasNext()); String freindIds = builder.toString(); Log.d("MSG:", "FND id:" + freindIds); if (freindIds.equals("")) { mUserInfo.setFriendsIds(freindIds); } else { freindIds = freindIds.substring(0, freindIds.length() - 1); mUserInfo.setFriendsIds(freindIds); } } if (userObj.getName() != null) { String name[] = userObj.getName().split(" "); /* * mUserInfo.setFirstName(name[0]); if (name[1] != null) { * mUserInfo.setLastName(name[1]); * * } */ if (name.length >= 2) { mUserInfo.setFirstName(name[0]); mUserInfo.setLastName(name[1]); } else if (name.length >= 1) { mUserInfo.setFirstName(name[0]); } } mUserInfo.setExpiresIn(String.valueOf(System.currentTimeMillis() + 600000)); } catch (TwitterException e) { Log.e(TAG, "Twitter login error"); } twitterHandler.isExit(String.valueOf(accessToken2.getUserId())); }
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); User user = twitter.showUser(args[0]); if (user.getStatus() != null) { System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText()); } else { // the user is protected System.out.println("@" + user.getScreenName()); } System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to delete status: " + te.getMessage()); System.exit(-1); } }
/** * Saving user information, after user is authenticated for the first time. You don't need to show * user to login, until user has a valid access toen */ private void saveTwitterInfo(AccessToken accessToken) { long userID = accessToken.getUserId(); User user; try { user = twitter.showUser(userID); String username = user.getName(); /* Storing oAuth tokens to shared preferences */ Editor e = mSharedPreferences.edit(); e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.putString(PREF_USER_NAME, username); e.commit(); } catch (TwitterException e1) { e1.printStackTrace(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); writeToSDCard(); btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter); lblUserName = (TextView) findViewById(R.id.lblUserName); btnGetTweets = (Button) findViewById(R.id.getTweets); btnShowOnMap = (Button) findViewById(R.id.showOnMap); btnUsers = (Button) findViewById(R.id.btnUser); btnFollowers = (Button) findViewById(R.id.btnFollower); mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); btnLoginTwitter.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { if (isTwitterLoggedInAlready()) { logoutFromTwitter(); } // Call login twitter function loginToTwitter(); finish(); } }); btnLogoutTwitter.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function logoutFromTwitter(); } }); btnGetTweets.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function getTweetsFromTwitter(); // finish(); } }); btnShowOnMap.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function Intent intent = new Intent(MainActivity.this, MapActivity.class); intent.putExtra("userID", USER_ID); startActivity(intent); finish(); } }); btnUsers.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Following.class); startActivity(intent); finish(); } }); btnFollowers.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Followers.class); startActivity(intent); finish(); } }); /** * This if conditions is tested once is redirected from twitter page. Parse the uri to get oAuth * Verifier */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present Log.e("Twitter oAuth tokens", "Please set your twitter oauth tokens first!"); // stop executing code by return return; } Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); btnLogoutTwitter.setVisibility(View.VISIBLE); btnLoginTwitter.setVisibility(View.GONE); btnGetTweets.setVisibility(View.VISIBLE); btnUsers.setVisibility(View.VISIBLE); btnShowOnMap.setVisibility(View.VISIBLE); btnFollowers.setVisibility(View.VISIBLE); // Show Update Twitter // lblUpdate.setVisibility(View.VISIBLE); // Getting user details from twitter // For now i am getting his name only USER_ID = accessToken.getUserId(); User user = twitter.showUser(USER_ID); String username = user.getName(); // Displaying in xml ui lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>")); } catch (Exception e) { // Check log for login errors e.printStackTrace(); Log.e("Twitter Login Error", "> " + e.getMessage()); } } } }
public void getTweets() { // tweetText.setText(""); String queryText = keyword.getText().toString(); if (queryText.matches("")) { Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show(); return; } // System.out.println("Keyword =="+ queryText); if (isConnected()) { String oauthAccessToken = mSharedPreferences.getString(Const.PREF_KEY_TOKEN, ""); String oAuthAccessTokenSecret = mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""); ConfigurationBuilder confbuilder = new ConfigurationBuilder(); Configuration conf = confbuilder .setOAuthConsumerKey(Const.CONSUMER_KEY) .setOAuthConsumerSecret(Const.CONSUMER_SECRET) .setOAuthAccessToken(oauthAccessToken) .setOAuthAccessTokenSecret(oAuthAccessTokenSecret) .build(); TwitterFactory tf = new TwitterFactory(conf); Twitter twitter = tf.getInstance(); try { // Query query = new Query(queryText); int tweetCount = 50; User user = twitter.showUser(queryText.trim()); long userId = user.getId(); List<Status> tweets = twitter.getUserTimeline(userId, new Paging(1, tweetCount)); // QueryResult result; // result = twitter.search(query); // List<Status> tweets = result.getTweets(); String[] resultStringSet; if (tweets.size() == 0) { resultStringSet = new String[1]; resultStringSet[0] = "No tweet found for this keyword. Please try some other keyword"; } else { resultStringSet = new String[tweets.size()]; } int i = 0; for (Status tweet : tweets) { final String text = "@" + tweet.getUser().getScreenName() + " - " + tweet.getText(); // System.out.println(tweet); resultStringSet[i++] = text; } final ArrayAdapter<String> resultAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultStringSet); list = (ListView) findViewById(R.id.resultList); list.post( new Runnable() { @Override public void run() { list.setAdapter(resultAdapter); // tweetText.append(text); // tweetText.append("\n"); // scrollView.fullScroll(View.FOCUS_DOWN); } }); } catch (TwitterException te) { Toast.makeText( this, "Please enter valid screen name of the twitter user", Toast.LENGTH_LONG) .show(); te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); return; // System.exit(-1); } buttonLogin.setText(R.string.label_disconnect); getTweetButton.setEnabled(true); } else { buttonLogin.setText(R.string.label_connect); } }
@SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.twitter); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().hide(); } cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog( twitter.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present alert.showAlertDialog( twitter.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // All UI elements btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus); btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter); txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus); lblUpdate = (TextView) findViewById(R.id.lblUpdate); lblUserName = (TextView) findViewById(R.id.lblUserName); // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); /** Twitter login button click event will call loginToTwitter() function */ btnLoginTwitter.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { // Call login twitter function } }); /** Button click event to Update Status, will call updateTwitterStatus() function */ btnUpdateStatus.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Call update status function // Get the status from EditText loginToTwitter(); } }); /** Button click event for logout from twitter */ btnLogoutTwitter.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function logoutFromTwitter(); } }); /** * This if conditions is tested once is redirected from twitter page. Parse the uri to get oAuth * Verifier */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Hide login button btnLoginTwitter.setVisibility(View.GONE); // Show Update Twitter lblUpdate.setVisibility(View.VISIBLE); txtUpdate.setVisibility(View.VISIBLE); btnUpdateStatus.setVisibility(View.VISIBLE); btnLogoutTwitter.setVisibility(View.VISIBLE); // Getting user details from twitter // For now i am getting his name only long userID = accessToken.getUserId(); User user = twitter.showUser(userID); String username = user.getName(); // Displaying in xml ui lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>")); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); } } } }