I'm trying to create a twitter client with twitter4j library. But still I'm not clear with the stuff and I couldn't find a good tutorial. Most of the tutorials are outdated. Mainly I want to know that, do I have to use OAuth everytime when I'm creating a Twitter Client? If not how should I do it (I mean, without getting a 'consumer-key' and 'consumer-secret' and just by entering username and password)? Any help would be appreciated. Thanks.
4 Answers
You have to register an app at http://dev.twitter.com/apps/ to get a consumer key and secret if you want to use twitter4j.
My app simply posts a tweet with an image and I was hoping to find a simple tweet function but found instead a labyrinth of authentication details and code threading issues.
To make it easier to just tweet with an image I have encapsulated twitter4j inside a wrapper JAR file that handles all the authentication and threading issues. It requires just a few lines of code (3 at a minimum) to work. The JAR file is called MSTwitter.jar.
MSTwitter.jar contains three files one of which is MSTwitter. At the top to this file are comments that explain how to use the JAR. They are repeated here:
To use MSTwitter.jar:
-Project setup:
-Create a twitter app on https://dev.twitter.com/apps/ to get:
-CONSUMER_KEY a public key(string) used to authenticate your app with Twitter.com
-CONSUMER_SECRET a private key(string) used to authenticate your app with Twitter.com
You don't need any thing else so authorization url etc are not important for this process
-Put twitter4j-core-3.0.2.jar and MSTwitter.jar files in your project's libs directory:
-You can download twitter4j from from http://twitter4j.org
-Register the jars in your project build path:
Project->Properties->Java Build Path->Libraries->Add Jar
->select the jar files you just added to your project's libs directory.
-Make AndroidManifest.xml modifications
-Add <uses-permission android:name="android.permission.INTERNET" /> inside manifest section (<manifest>here</manifest>)
-Add <uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside manifest section
-Add <uses-permission android:name="android.permission.BROADCAST_STICKY" /> inside manifest section
-Add <activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" /> inside application section.
-Add <service android:name="com.mindspiker.mstwitter.MSTwitterService" /> inside application section.
-Code to add to you calling activity
-Define a module MSTwitter variable.
-In onCreate() allocate a module level MSTwitter variable
ex: mMTwitter = new MSTWitter(args);]
-Add code to catch response from MSTwitterAuthorizer in your activity's onActivityResult()
ex:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ mMSTwitter.onCallingActivityResult(requestCode, resultCode, data); }
-Call startTweet(String text, String imagePath) on your MSTwitter object instance.
if you image is held in memory and not saved to disk call
MSTwitter.putBitmapInDiskCache() to save to a temporary file on disk.
-(Optional) Add a MSTwitterResultReceiver to catch MSTwitter events which are
fired at various stages of the process.
MSTwitterResultReceiver events:
-MSTWEET_STATUS_AUTHORIZING the app is not authorized and the authorization process is starting.
-MSTWEET_STATUS_STARTING the app is authorized and sending the tweet text and image is starting.
-MSTWEET_STATUS_FINSIHED_SUCCCESS the tweet is done and was successful.
-MSTWEET_STATUS_FINSIHED_FAILED the tweet is done and failed to complete.
Notes:
-If your project compiles but crashes when any twwiter4j object is instantiated a possible cause may be trying to add the jars as external jars instead of the suggested method above. If your libraries directory already exists but is called 'lib', change the name to 'libs'. Sounds crazy I know, but works in some situations.
-To prevent large images from being passed around between intents images should be cached to disk and retrieved when used. Only the file name is passed between intents.
-To perform tasks on a separate thread that passes information to and from activities, which could be destroyed at any time (phone call, screen orientation change, etc.), a method using intent services to perform the work and sticky broadcasts to pass the data was employed. For more on this method and why it was used check out: http://stackoverflow.com/questions/1111980/how-to-handle-screen-orientation-change-when-progress-dialog-and-background-thre/8074278#8074278
The below files are from a sample project which posts a tweet with an image.
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.imagetweettester" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.mindspiker.mstwitter.MSTwitterService" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
<activity android:name="com.example.imagetweettester.MainActivity" android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.mindspiker.mstwitter.MSTwitterAuthorizer" />
<service android:name="com.mindspiker.mstwitter.MSTwitterService" />
</application>
</manifest>
MainActivity.java
package com.example.imagetweettester;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.mindspiker.mstwitter.MSTwitter;
import com.mindspiker.mstwitter.MSTwitter.MSTwitterResultReceiver;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Consumer Key generated when you registered your app at https://dev.twitter.com/apps/ */
public static final String CONSUMER_KEY = "yourConsumerKeyHere";
/** Consumer Secret generated when you registered your app at https://dev.twitter.com/apps/ */
public static final String CONSUMER_SECRET = "yourConsumerSecretHere";
/** module level variables used in different parts of this module */
private MSTwitter mMSTwitter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup button to call local tweet() function
Button tweetButton = (Button) findViewById(R.id.button1);
tweetButton.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View v) {
tweet();
}
});
// make a MSTwitter event handler to receive tweet send events
MSTwitterResultReceiver myMSTReceiver = new MSTwitterResultReceiver() {
@Override
public void onRecieve(int tweetLifeCycleEvent, String tweetMessage) {
handleTweetMessage(tweetLifeCycleEvent, tweetMessage);
}
};
// create module level MSTwitter object.
// This object can be destroyed and recreated without interrupting the send tweet process.
// So no need to save and pass back in savedInstanceState bundle.
mMSTwitter = new MSTwitter(this, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//This MUST MUST be done for authorization to work. If your get a MSTWEET_STATUS_AUTHORIZING
// message and nothing else it is most likely because this is not being done.
mMSTwitter.onCallingActivityResult(requestCode, resultCode, data);
}
/**
* Send tweet using MSTwitter object created in onCreate()
*/
private void tweet() {
// assemble data
// get text from layout control
EditText tweetEditText = (EditText) findViewById(R.id.editText1);
String textToTweet = tweetEditText.getText().toString();
// get image from resource
Bitmap imageToTweet = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// use MSTwitter function to save image to file because startTweet() takes an image path
// this is done to avoid passing large image files between intents which is not android best practices
String tweetImagePath = MSTwitter.putBitmapInDiskCache(this, imageToTweet);
// start the tweet
mMSTwitter.startTweet(textToTweet, tweetImagePath);
}
@SuppressLint("SimpleDateFormat")
private void handleTweetMessage(int event, String message) {
String note = "";
switch (event) {
case MSTwitter.MSTWEET_STATUS_AUTHORIZING:
note = "Authorizing app with twitter.com";
break;
case MSTwitter.MSTWEET_STATUS_STARTING:
note = "Tweet data send started";
break;
case MSTwitter.MSTWEET_STATUS_FINSIHED_SUCCCESS:
note = "Tweet sent successfully";
break;
case MSTwitter.MSTWEET_STATUS_FINSIHED_FAILED:
note = "Tweet failed:" + message;
break;
}
// add note to results TextView
SimpleDateFormat timeFmt = new SimpleDateFormat("h:mm:ss.S");
String timeS = timeFmt.format(new Date());
TextView resultsTV = (TextView) findViewById(R.id.resultsTextView);
resultsTV.setText(resultsTV.getText() + "\n[Message received at " + timeS +"]\n" + note);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" tools:context=".MainActivity" >
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Start Tweet" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text to tweet:" />
<EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:text="Test tweet text" >
<requestFocus />
</EditText>
<ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Results:" />
<TextView android:id="@+id/resultsTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" />
</LinearLayout>

- 1,437
- 1
- 14
- 22
-
1Hi MindSpiker, do you host this lib of yours somewhere as an open source? It works allright, but it doesn't provide everything I need so I wanted to code it up to my needs... – Nemanja Kovacevic Mar 19 '13 at 19:21
-
The jar includes the source so you could copy it from there. If you want the project you can download at http://www.mindspiker.com/Projects/MSTwitter/MSTwitter.zip. – MindSpiker Mar 20 '13 at 01:05
-
Amazing. Just added required jars and edited my API key and secret key. And whoa, Its done...! Great work.. – YuDroid May 11 '13 at 13:32
-
MindSpiker, I used your jar and the sample code to try to implement within my own app. When I actually tweet, no tweet shows up on the test page. Then, the callback directs to a page that just shows a page that "does not exist", with a search box with the word "login" in it. How do I get around these two errors? – user2163853 May 22 '13 at 01:15
-
@MindSpiker I tried a demo project with your library. It works fine. But is there any way to log the user out? User may want to log out from the account any time. I just need a logic for logging user out. Thank you. – Geek Jul 05 '13 at 11:03
-
@MindSpiker This works ok, but you have to unregister the `MSTwitterResultReceiver` somehow... I couldn't do it...because this causes an error – AlexAndro Nov 17 '13 at 16:19
I used the jar file referenced in MindSpiker's answer:
If I put a random Callback URL in my twitter app configuration:
My app opens a browser, I login and it tries to call the callback url it's creating an error inside Twitter's web.
If I leave that blank: I get this error:
04-02 13:48:49.654: E/MSTwitter(7983): Tweeter Error: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
04-02 13:48:49.654: E/MSTwitter(7983): <?xml version="1.0" encoding="UTF-8"?>
04-02 13:48:49.654: E/MSTwitter(7983): <hash>
04-02 13:48:49.654: E/MSTwitter(7983): <request>/oauth/request_token</request>
04-02 13:48:49.654: E/MSTwitter(7983): <error>Desktop applications only support the oauth_callback value 'oob'</error>
04-02 13:48:49.654: E/MSTwitter(7983): </hash>
04-02 13:48:49.654: E/MSTwitter(7983): 10f5ada3-e574402b: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
04-02 13:48:49.654: E/MSTwitter(7983): <?xml version="1.0" encoding="UTF-8"?>
04-02 13:48:49.654: E/MSTwitter(7983): <hash>
04-02 13:48:49.654: E/MSTwitter(7983): <request>/oauth/request_token</request>
04-02 13:48:49.654: E/MSTwitter(7983): <error>Desktop applications only support the oauth_callback value 'oob'</error>
04-02 13:48:49.654: E/MSTwitter(7983): </hash>
what am I doing wrong here?

- 2,995
- 3
- 17
- 28
-
From the error message it looks like your consumer and secret are not set. They are set in the above activity file when the MSTwitter object is created with MSTwitter(this, CONSUMER_KEY, CONSUMER_SECRET, myMSTReceiver). These values need to be obtained from twitter by making an application in their system at dev.twitter.com/apps/ – MindSpiker Apr 02 '13 at 18:05
-
MindSpike: thanks for your reply. unfortunatly I had set the keys already. I am supposed to leave the callback url blank in dev.twitter.com/apps/ right ? – franck Apr 02 '13 at 18:41
-
The callback URL used in MSTwitter is "com-mindspiker-mstwitter" This is passed to twitter.com as part of the process to get the request URL that is opened when the user authorizes with their user id and password. Process happens in MSTwitterService.processGetAuthURL(). Because the call back url is sent durring the process I don't think it has to match whatever is entered as the callback url in dev.twitter.com/apps/. Also just checked my twitter app and the my callback url is complete unrelated to the one used in MSTwitter jar. – MindSpiker Apr 04 '13 at 19:50
-
Also you say your "app opens a browser, I logon". Does this mean you call MSTwitter from an activity, it (MSTwitter) opens a browser and then errors out after you press "Authorize App"? – MindSpiker Apr 04 '13 at 20:48
-
I'm facing a similar problem here, when I call mMSTwitter.startTweet("Description for twitter", null); I receive the same auth error message. I don't see any browser opening, just throws that. My settings on twitter are: Access Level: Read/Write Callback URL: none Sign in with Twitter: Yes Your access token: I have the two tokens and access level read and write. Any clue? Thanks – zegnus Apr 06 '13 at 10:33
-
1
-
@MindSpiker Yes, my app is opening a browser, asking the question: Authorize "my app" to use your account. then I click on Authorize app, then I get a new page "redirecting back to your application" for 1 second, then I get a third page saying "sorry that page doesn't exists" with an input box with "login" written it and a "search button". I configured the callback URL to my webpage URL. – franck Apr 10 '13 at 19:31
-
@zegnus : what did you put as a callback ? is there some special page php answering for it on your server ? – franck Apr 10 '13 at 19:37
-
should I click "Allow this application to be used to Sign in with Twitter "When enabled your application can be used to "Sign in with Twitter". When disabled your application will not be able to use /oauth/authenticate and any request to it will instead redirect the user to /oauth/authorize" in my application settings ? If I do I have a different behavior: I get to the first authorize page and but It gets back to the same back when I click "sign", If I click cancel I do get back to my application though – franck Apr 10 '13 at 19:57
-
@franck On my twitter.com app that is working fine I have Sign in with Twitter=no. Here are all of my app settings with private info X'ed out: Organization None, Organization website None, Access level Read and write, Consumer key xxxx, Consumer secret xxxx, Request token URL https://api.twitter.com/oauth/request_token, Authorize URL https://api.twitter.com/oauth/authorize, Access token URL https://api.twitter.com/oauth/access_token, Callback URL http://xxxxx.com, Sign in with Twitter No, Access token xxxxx, Access token secret xxxx, Access level Read and write – MindSpiker Apr 17 '13 at 01:58
First I want to thanks you MindSpiker for this awesome wrapper. I can't believe how hard is send a simple text status on Android. In iOS is pretty simple using the right library. And also I want to contribute with your library with a small fix.
Like some users I also got the "Sorry that page doesn't exists" webpage after I authorize my app so I downloaded your code and debugged from the source. For a weird reason the shouldOverrideUrlLoading method on MSTwitterAuthorizer.java file is not triggering in the right way. Here is the original code:
private class TwitterWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// see if Twitter.com send back a url containing the callback key
if (url.contains(MSTwitter.CALLBACK_URL)) {
// we are done talking with twitter.com so check credentials and finish interface.
processResponse(url);
finish();
return true;
} else {
// keep browsing
view.loadUrl(url);
return false;
}
}
}
I suggest to add a onPageStarted event:
private class TwitterWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.contains(MSTwitter.CALLBACK_URL)) {
// we are done talking with twitter.com so check credentials and finish interface.
processResponse(url);
finish();
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// see if Twitter.com send back a url containing the callback key
if (url.contains(MSTwitter.CALLBACK_URL)) {
// we are done talking with twitter.com so check credentials and finish interface.
processResponse(url);
finish();
return true;
} else {
// keep browsing
view.loadUrl(url);
return false;
}
}
}
And then I could make it work on Android 2.2 :)
Please upload your code on GitHub, you could add some extra methods like get the timeline or anything else. The authentication thing is very annoying.

- 170
- 2
- 11
-
1Thanks for the mod. The project is on Github so if you use git hub you can make the changes and push them up. If not I will include the change when I get around to a few other changes people who used it suggested. The github project is located at http://github.com/mindSpiker/MSTwitter . – MindSpiker Apr 24 '13 at 20:29
-
I did another fix to your code (I was getting a leak for the broadcaster). I'm thinking to make it a complete Twitter wrapper. – noisedan Apr 29 '13 at 20:28
Ahh, you also need to set the callback url (any webpage you want, it's doesn't matter) in the twitter dev app settings page :)

- 170
- 2
- 11