Android Compose Tweets (Twitter) - Androhub

Compose Tweet Banner

Android Compose Tweets (Twitter)

Hi to all in previous two articles we learnt how to integrate Twitter authentication in our app and show different kind of Twitter Timelines in our app. Today we will learn a little bit more about Twitter APIs i.e Composing Tweets from our App and sharing Image and Text using Twitter Compose API.

Prerequisite

1. Twitter Authentication.

2. Alert Dialog.

3. Runtime Permissions.

4. Picking Image from Gallery.

5. Capture Image using Camera.

6. Broadcast Receiver.

Please go through above given prerequisite link so that you will better understand the article.

VIDEO DEMO

TweetComposer basically provides two ways to compose Tweets:

1. Launch the Twitter application’s Tweet Composer  ;  A feature-rich composer which supports attaching images and videos.
2. Launch the Twitter Kit Native Composer  :  A lightweight composer which lets users compose Tweets from within your application.

Launching Twitter Application’s Tweet Composer

To compose Tweet using this way use the below simple code:

The image Uri should be a Uri using the content:// scheme. For example,

If the Twitter app is not installed, the intent will launch twitter.com in a browser, but the specified image will be ignored. For more details on correctly setting up a FileProvider see Setup Sharing.

Launching Twitter Application Composer
Launching Twitter Application Composer

Sending Tweet
Sending Tweet

For devices who doesn’t have Twitter App installed then the browser will open like below with pre-fill text you passed.

Device without Twitter App
Device without Twitter App

Launching Twitter Native Kit Composer

To compose Tweet using this way use the below sample code:

After attempting to post a Tweet, the TweetUploadService broadcasts an Intent with the action values:

  1. com.twitter.sdk.android.tweetcomposer.UPLOAD_SUCCESS (for success) : The Intent will contain an extra value with the Tweet ID of the created Tweet.
  2. com.twitter.sdk.android.tweetcomposer.UPLOAD_FAILURE (for failure) : The Intent will contain a copy of the original intent which could be used to retry the upload.
  3. com.twitter.sdk.android.tweetcomposer.TWEET_COMPOSE_CANCEL (for dismissing the compose dialog) : For cancel there is no extra value.

You can create a BroadcastReceiver to receive these Intents.

Don’t forget to add your BroadcastReceiver to the application AndroidManifest.xml.

Launching Twitter Native Composer
Launching Twitter Native Composer

On successful tweet post you will be able to see that Tweet inside your Tweet timeline.

On Twitter Upload Successful
On Twitter Upload Successful

Example

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.

3. On syncing completion create an Application java class naming MyApplication.java where we will initialise Twitter.

4. Now declare create Application in AndroidManifest.xml.

5. Lets create an xml layout naming activity_main.xml and place the following code into it. In this class i have taken two Button to show both types of Compose Tweets and an ImageView to select and show picked/captured Image.

 6. Now we will see how to pick  image from Gallery and capture image from Camera. For this we will be using FileProvider.
FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.
The increased level of file access security offered by a content URI makes FileProvider a key part of Android’s security infrastructure.
To do this define FileProvider in your manifest file:

Set the android:authorities attribute to a URI authority based on a package name of your project.For example, if you control the package name com.example you should use the authority com.example.file_provider. Set the android:exported attribute to false; the FileProvider does not need to be public. Set the android:grantUriPermissions attribute to true, to allow you to grant temporary access to files.

A FileProvider can only generate a content URI for files in directories that you specify beforehand. To specify a directory, specify the its storage area and path in XML, using child elements of the <paths> element. For example, the following paths element tells FileProvider that you intend to request content URIs for the images/ subdirectory of your private file area.

There are lot more options to create and add your provider paths that you can check here.

7. Now open MainActivity.java and add the below code to it.

In this class the below code is responsible to show how to get URI using FileProvider:

8. After adding code to MainActivity.java there are some Utils java class that you should be needing.

  • CamerUtils.java : To check if device support Camera or not.

  • FileNameCreation.java : To create image file in directory using FileProvider for Camera to capture image and store in respective directory.

  • MarshMallowPermission.java : To check Runtime Permission for Marshmallow+ API levels..

9. Don’t forget to add below mentioned permissions to AndroidManifest.xml.

Your AndroidManifest will look like this:

10. For FileProvider xml path use the below code:

11. Finally all done , now you can also create app to Compose Tweets.

Thanks. :)

NOTE : After downloading don’t forget to place your API Key and Secret inside MyApplication.java.

15 Comments

shakir khan
Wednesday, December 26th, 2018

This is the best article , solve my all issues..Thank you for the article

Ramashish Prajapati
Thursday, January 3rd, 2019

How to send video with hashtag in twitter like image your sending??

Dr. Droid
Friday, January 4th, 2019

Hi Ramashish,

I had done research about how to share video with hashtag and i don’t think so its possible. Please go through the below link:

https://stackoverflow.com/questions/46659942/how-to-share-video-in-twitter-using-twitter-kit-3-in-the-android

Thanks

Dharmesh Patel
Monday, February 11th, 2019

I have used this code to compose tweet but getting TweitterSession error. Here, I attached log, please help me to resolved this issue.

final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
final Intent intent = new ComposerActivity.Builder(MainActivity.this)
.session(session)
.text(“Love where you work”)
.hashtags(“#twitter”)
.createIntent();
startActivity(intent);

Logs::
TwitterSession must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: TwitterSession must not be null
at com.twitter.sdk.android.tweetcomposer.ComposerActivity$Builder.session(ComposerActivity.java:95)
at com.example.inextrix.twittereazydemo.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:6251)

Dr. Droid
Monday, February 11th, 2019

Hi Dharmesh,

I think you have not authenticated user before composing. Check this shareUsingTwitterNativeComposer(View view) method where i am checking whether user session is null or not and if it is null then i am authenticating user.

Thanks

Dharmesh Patel`
Tuesday, March 12th, 2019

Hello,
Thanks for help me. My above issue is solved app twitter working fine but now after some days I got error that com.twitter.sdk.android.core.TwitterAuthException: Failed to get request token.

Please help to resolved this error.

Dr. Droid
Tuesday, March 12th, 2019

Hi Dharmesh,

Can you tell me that it always gives the same error while doing fresh install of the application or on specific scenario this issue is coming?

Thanks

Dharmesh Patel
Tuesday, March 12th, 2019

When twitter app is not installed in device then this issue comes(If twitter app is installed then it open app). Moreover, this error I found in log.
Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings

Can you please tell me where I need to set callback url in code?

Dr. Droid
Tuesday, March 12th, 2019

Hi Dharmesh,

In my previous article about Twitter Auth i mentioned how to set Callback URL.

Actually Callback URL should be set in Apps under Twitter site.

Thanks

Dharmesh Patel
Tuesday, March 12th, 2019

Ok. Thanks.

Rishabh Raj
Sunday, July 12th, 2020

How can i increase the tweet limit from 140 to 280 as per latest update?

Dharmesh Patel
Friday, August 7th, 2020

I faced this error in Android 10.
/sdcard/hive.jpg: open failed: EACCES (Permission denied)

This is provider in Manifest.

provider_paths.xml

Uri in Java class.

Uri data = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + “.provider”, new File(“/sdcard/hive.jpg”));

Dr. Droid
Wednesday, August 12th, 2020

Hi Dharmesh,

Have u added the run-time permissions?

Thanks

Fernando
Tuesday, October 13th, 2020

Hello Doctor. Thanks for this important update. Please, when I download the source code and upload it to the Studio, I can use the native compose tweet sending images but when I create a new project and do everything in the tutorial I can only use the native compose tweet to send text, when I send an image this does not work and no error appears. I already verify everything is correct according to the tutorial, maybe you know what the problem is? I can send you my code, the donation is guaranteed.

Dr. Droid
Friday, October 16th, 2020

Hi Fernando,

Sure please share your code. Let me check it.

Thanks

Post comment

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