In previous three tutorials we have learnt so many things about Twitter APIs which includes:
So Today we will learn a bit more about Twitter API i.e Show Tweets. TweetUi API provides Tweet views to render Tweets in your app via code or in XML.
Before moving further please go through all my three previous articles about Twitter to get a better understanding.
TweetUi provides the TweetView and CompactTweetView views for rendering Tweets. The view constructors take a context, the Tweet to be rendered, and an optional style.
Tweets can be requested through the TwitterCore Tweet API or TweetUtils which will cache recent requests. Here is an example using TweetUtils to load a Tweet and construct a TweetView and CompactTweetView in the success callback.
TweetView
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.main_layout); final long tweetId = 952933941702545408L; TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { myLayout.addView(new TweetView(MainActivity.this, result.data)); } @Override public void failure(TwitterException exception) { // Toast.makeText(...).show(); } }); |
CompactTweetView
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.main_layout); final long tweetId = 952933941702545408L; TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { myLayout.addView(new CompactTweetView(MainActivity.this, result.data)); } @Override public void failure(TwitterException exception) { // Toast.makeText(...).show(); } }); |
The TweetView and CompactTweetView can be inflated from an XML layout as well. For this usage, the tw__tweet_id attribute must specify the Tweet id and the Tweet will be loaded and rendered upon inflation.
TweetView
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <com.twitter.sdk.android.tweetui.TweetView android:id="@+id/tweet_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:tw__tweet_id="954329648879587328"/> </LinearLayout> |
CompactTweetView
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <com.twitter.sdk.android.tweetui.CompactTweetView android:id="@+id/tweet_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:tw__tweet_id="954329648879587328"/> </LinearLayout> |
NOTE : You must use the layout parameters android:layout_width=”match_parent” and android:layout_height=”wrap_content”.
You can handle the Tweet Views actions by setting a callback method which you can listen and do the stuff according to that. On setting a Callback method you can listen events like favourite event. If user is guest user then you have to ask user to do login first. Twitter will throw an exception TwitterAuthException by which you get to know that user is not authenticated. Below is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// launch the login activity when a guest user tries to favorite a Tweet final Callback<Tweet> actionCallback = new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { // Intentionally blank } @Override public void failure(TwitterException exception) { if (exception instanceof TwitterAuthException) { // launch custom login flow } } }; |
After creating a callback set the callback to Tweet like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.main_layout); final long tweetId = 952933941702545408L; TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { final TweetView tweetView = new TweetView(MainActivity.this, result.data); tweetView.setOnActionCallback(actionCallback)//set callback myLayout.addView(tweetView);/add view } @Override public void failure(TwitterException exception) { // Toast.makeText(...).show(); } }); |
If you have implemented Tweet using XML then use below code to set callback :
1 2 3 4 |
//find id of TweetView TweetView tweetView = findViewById(R.id.tweet_view); //set callback action to TweetView to listen favourite event tweetView.setOnActionCallback(actionCallback); |
You can style TweetViews by using simple line of code. Use below code to set style in java code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.main_layout); final long tweetId = 952933941702545408L; TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { myLayout.addView(new TweetView(MainActivity.this, result.data, R.style.tw__TweetDarkWithActionsStyle));//set style } @Override public void failure(TwitterException exception) { // Toast.makeText(...).show(); } }); |
Use below code to set style in XML code:
1 2 3 4 5 6 |
<com.twitter.sdk.android.tweetui.TweetView android:id="@+id/tweet_view" style="@style/tw__TweetDarkWithActionsStyle" android:layout_width="match_parent" android:layout_height="wrap_content" twittersdk:tw__tweet_id="954329648879587328"/> |
1. Create an App on Twitter and get API Key and Secret. To know how to get these things check my previous tutorial.
2. After getting API Key and Secret open build.gradle and add the following dependencies to it and sync the gradle.
1 2 3 |
//Twitter API Dependency compile 'com.twitter.sdk.android:twitter-core:3.1.1' compile 'com.twitter.sdk.android:tweet-ui:3.1.1' |
3. On syncing completion create an Application java class naming MyApplication.java where we will initialise Twitter.
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 |
package com.twitter_show_tweets_demo; import android.app.Application; import android.util.Log; import com.twitter.sdk.android.core.DefaultLogger; import com.twitter.sdk.android.core.Twitter; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterConfig; /** * Created by sonu on 22/01/18. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //config twitter with API Key and Secret Key TwitterConfig config = new TwitterConfig.Builder(this) .logger(new DefaultLogger(Log.DEBUG)) .twitterAuthConfig(new TwitterAuthConfig("CONSUMER_KEY", "CONSUMER_SECRET")) .debug(true) .build(); //initialize twitter Twitter.initialize(config); } } |
4. Now declare create Application in AndroidManifest.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<application android:name=".main.MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".main.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> |
5. Lets create an xml layout naming activity_main.xml and place the following code into it. In this class I have taken two Tweet Views one TweetView and another CompactTweetView.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.twitter_show_tweets_demo.MainActivity"> <LinearLayout android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tweet_view" android:textColor="@android:color/black" android:textSize="18sp" /> <!-- TweetView with Dark Style theme, here pass any Tweet Id in place of tw__tweet_id --> <com.twitter.sdk.android.tweetui.TweetView android:id="@+id/tweet_view" style="@style/tw__TweetDarkWithActionsStyle" android:layout_width="match_parent" android:layout_height="wrap_content" app:tw__tweet_id="954329648879587328" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="@string/compact_tweet_view" android:textColor="@android:color/black" android:textSize="18sp" /> <!-- CompactTweetView with Light Style theme, here pass any Tweet Id in place of tw__tweet_id --> <com.twitter.sdk.android.tweetui.CompactTweetView android:id="@+id/compact_tweet_view" style="@style/tw__TweetLightWithActionsStyle" android:layout_width="match_parent" android:layout_height="wrap_content" app:tw__tweet_id="953599133318819843" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="@string/tweet_view_runtime" android:textColor="@android:color/black" android:textSize="18sp" /> <!-- Here the runtime Tweet will be shown and will be added in runtime --> </LinearLayout> </android.support.v4.widget.NestedScrollView> |
If you don’t know how to get TweetId from a Tweet see the below image:
6. Now open MainActivity.java and add the below code to it.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
package com.twitter_show_tweets_demo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.Toast; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.Twitter; import com.twitter.sdk.android.core.TwitterAuthException; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.models.Tweet; import com.twitter.sdk.android.tweetui.CompactTweetView; import com.twitter.sdk.android.tweetui.TweetUtils; import com.twitter.sdk.android.tweetui.TweetView; public class MainActivity extends AppCompatActivity { private LinearLayout mainLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //find the id of main layout mainLayout = findViewById(R.id.main_layout); //find id of TweetView TweetView tweetView = findViewById(R.id.tweet_view); //set callback action to TweetView to listen favorite event tweetView.setOnActionCallback(actionCallback); //find id of CompactTweetView CompactTweetView compactTweetView = findViewById(R.id.compact_tweet_view); //set callback action to CompactTweetView to listen favorite event compactTweetView.setOnActionCallback(actionCallback); //load runtime Tweet loadTweet(); } private void loadTweet() { //use any TweetID final long tweetId = 952933941702545408L; //start loading tweet and pass TweetID TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { //create TweetView or CompactTweetView with "result.data" final TweetView tweetView = new TweetView(MainActivity.this, result.data, R.style.tw__TweetDarkWithActionsStyle); //set action callback tweetView.setOnActionCallback(actionCallback); //finally add created Tweet to LinearLayout mainLayout.addView(tweetView); } @Override public void failure(TwitterException exception) { //show toast if some exception occurs Toast.makeText(MainActivity.this, "Failed to show Tweet.", Toast.LENGTH_SHORT).show(); } }); } // launch the login activity when a guest user tries to favorite a Tweet final Callback<Tweet> actionCallback = new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { // Intentionally blank } @Override public void failure(TwitterException exception) { if (exception instanceof TwitterAuthException) { Toast.makeText(MainActivity.this, "User is guest.", Toast.LENGTH_SHORT).show(); //launch login activity from here //ask user to login } } }; } |
7. Don’t forget to add INTERNET permissions to AndroidManifest.xml.
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.twitter_show_tweets_demo"> <!-- permission required to fetch Tweet --> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
8. Finally all done , see so simple. Now you can also create TweetViews.
Thanks.
NOTE : After downloading don’t forget to place your API Key and Secret inside MyApplication.java.
Subscribe to us and get the latest news.
5 Comments
Narendra
Sunday, April 15th, 2018Is it okay to have CONSUMER_SECRET in app side code?
Dr. Droid
Sunday, April 15th, 2018Hi Narendra,
No it is not okay to have your any API KEYs inside app code. There is a way to hide your API Keys , I am sharing one link just go through it.
https://medium.com/code-better/hiding-api-keys-from-your-android-repository-b23f5598b906
Thanks
Rozy Mumbai
Tuesday, November 6th, 2018hi
Nani
Wednesday, December 2nd, 2020Hi,
thanks for the tutorial,
In this tutorial showing like and share options only. i want to show retweet options to my users for retweet the post. Please reply
Thanks in advance
Dr. Droid
Wednesday, December 2nd, 2020Hi Nani,
This is the UI provided by Twitter SDK so only the Like and share buttons are only available.
Thanks