How to Integrate Twitter in your Android App

Among one thousand and one ways to push the graph of social engagement, we suggest integration of Twitter on Android. Considering its tremendous success, we have demonstrated below on how can your App be easily integrated with Twitter. Moreover, the sample also uses App42 Social Service API.

tweet list status How to Integrate Twitter in your Android App
Topics Covered
1. How to create an App on Twitter & generate Consumer & Secret-Key
2. How to authenticate Twitter User with your android App
3. How to show Tweets along with user details
4. How to re-tweet the tweets again
5. How to update your Twitter status using App42 SocialService API

# Running Sample
1. Create a Twitter application to receive required keys
2. Once you have logged in your Twitter account, click on ‘Create button’ to make a new application
3. Find your Consumer Key and Secret Key here in ‘OAuth’ settings option
4. Now, Register with App42 platform
5. Once you are on Quick start page after registration, Create an app
6. If you are already registered, login to AppHQ console and create an app from App Manager Tab
7. Download the project from here and import it in the eclipse
8.Open Constants.java file and make the changes given below

1
2
3
A. Change CONSUMER_KEY with your Consumer key from step 5 at line no 7.
B. Change CONSUMER_SECRET with your Consumer secret from step 5 at line no 8.
C. Change API_KEY and SECRET_KEY that you have received in step 7 or 8 at line number 10 and 11..

9.  Here, we are using twitter4j-core-3.0.3.jar for Twitter  integration
10.  Build your android App and install on any android device


get started How to Integrate Twitter in your Android App

auth How to Integrate Twitter in your Android App

# Design Details: 
Authorization With Twitter : To use Twitter API in your android application, you have to authorize the App. As a sample, I have authorized my application in TwitterApp.java file.

1. We require CONSUMER_KEY and CONSUMER_SECRET here.

2. Once your application is authorized , you can use Twitter API directly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void authorizeApp() {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
        configurationBuilder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
        Configuration configuration = configurationBuilder.build();
        twitter = new TwitterFactory(configuration).getInstance();
        try {
            requestToken = twitter.getOAuthRequestToken(Constants.CALLBACK_URL);
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(requestToken.getAuthenticationURL()));
            this.startActivity(intent);
            finish();
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    }

Handle Authorization callback: After you have authorized, you have to handle callback and save authorization details so that it doesn’t ask you for details again and again.
This is done in TwitterApp.java file.
1. Here, we get Accesstoken that shows that authorization is done.
2. Using this AccessToken, we will get our authToken , authTokenSecert and screenName. We will save these details.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protected void handleCallback() {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(Constants.CALLBACK_URL)) {
            String verifier = uri
                    .getQueryParameter(Constants.IEXTRA_OAUTH_VERIFIER);
            try {
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);
                Editor e = mSharedPreferences.edit();
                e.putString(Constants.PREF_KEY_TOKEN, accessToken.getToken());
                e.putString(Constants.PREF_KEY_SECRET,
                        accessToken.getTokenSecret());
                e.putString(Constants.PREF_KEY_USER,
                        accessToken.getScreenName());
                e.commit();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    }

Load Tweet-list: Following method is used to load the user Tweets only if the user is authorized. It takes authToken, authTokenSecert as an argument that are saved in Shared Preferences of android device. This is written in TwitterService.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void loadTweets(final String twitterToken, final String twitterSecret,
            final MyTwitterListener callBack) {
        final Handler callerThreadHandler = new Handler();
        new Thread() {
            @Override
            public void run() {
                try {
                    final ArrayList myTweets = getTwitterList(twitterToken,
                            twitterSecret);
                    callerThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onTweetList(myTweets);
                        }
                    });
                } catch (final Exception ex) {
                    callerThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onError(ex.toString());
                            }
                        }
                    });
                }
            }
        }.start();
    }

Build Tweet-list: The function mentioned below makes the Tweet-list along with the desired Tweet information. This function is written in TwitterService.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private ArrayList getTweets(Twitter twitter) {
        ArrayList tweetsList = new ArrayList();
        try {
            ResponseList response = twitter.getUserTimeline();
            for (int i = 0; i < response.size(); i++) {
                TwitterInfo tweetInfo = new TwitterInfo();
                Status status = response.get(i);
                tweetInfo.setText(status.getText());
                tweetInfo.setCreatedAt(status.getCreatedAt());
                tweetInfo.setCount(status.getRetweetCount());
                tweetInfo.setName(status.getUser().getName());
                tweetInfo.setPicurl(status.getUser().getProfileImageURL());
                tweetsList.add(tweetInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tweetsList;
    }
update status How to Integrate Twitter in your Android App

Update Twitter Status: Using App42 SocialService API,
we can easily update our Twitter Status. 
This is written in TwitterService.java file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void upDateStatus(final String userName, final String twitterToken,
		final String twitterSecret, final String status,
		final MyTwitterListener callBack) {
	final Handler callerThreadHandler = new Handler();
	new Thread() {
	@Override
	public void run() {
		try {
			Social socialObj = socialService.linkUserTwitterAccount(
				userName, twitterToken, twitterSecret,
				Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
			socialService.updateTwitterStatus(userName, status);
			callerThreadHandler.post(new Runnable() {
				@Override
				public void run() {
					callBack.onStatusUpdate();
					}
			});
		} catch (final Exception ex) {
			callerThreadHandler.post(new Runnable() {
				@Override
				public void run() {
					if (callBack != null) {
						callBack.onError(ex.toString());
					}
				}
			});
			}
		}
	}.start();
}

If you have questions or need any further assistance, do write to us at  support@shephertz.com.

twitter How to Integrate Twitter in your Android Appfacebook How to Integrate Twitter in your Android Appgoogle How to Integrate Twitter in your Android Applinkedin How to Integrate Twitter in your Android Apppinterest How to Integrate Twitter in your Android Appreddit How to Integrate Twitter in your Android Appstumbleupon How to Integrate Twitter in your Android Apptumblr How to Integrate Twitter in your Android App

Leave a Reply

Your email address will not be published. Required fields are marked *


5 − = zero

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>