Twitter Integration in android using twitter4j-4.0.1 - android

I am try to integrate twitter in android I have followed tutorial from following link http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
But I am facing an exception in loginwithTwitter function at these lines
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
I got e.getMessage() as null and exception occures at this line
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
Please help me solve this problem. I have also searched on internet and others queries like this on stackoverflow like Android twitter login not working
and Twitter Login Authentication in Android?
So kindly help me I am using twitter4j-4.0.1

I was having the same problem. I referred to this tutorial and it works - http://hintdesk.com/how-to-tweet-in-twitter-within-android-client/comment-page-1/
and also they have updated to twitter4j-core-4.0.1
Source code can be found here - https://bitbucket.org/hintdesk/android-how-to-tweet-in-twitter-within-android-client

Example code is at "https://github.com/gingerdroids/TwitterLogin".
I had difficulty getting Twitter login with Android and twitter4j going. Finally got there and uploaded a small sample app TwitterLogin to GitHub.

Related

How to send an image as direct message with twitter in android?

I want to send an image with text to a follower using twitter4j. I am able to send a direct message like this:
twitter.sendDirectMessage(twitterID, message);
Now, I can't figure out how to send an image as direct message. I did this for posting a tweet, which works:
StatusUpdate status = new StatusUpdate(message);
status.setMedia(pathOfTheFileToSend);
twitter.updateStatus(status);
So is it possible to send a image as direct message in twitter with the library twitter4j?
Thanks in advance.
First it's worth noting what Twitter4j does. It provides a good abstraction and bindings to Twitter's REST API in Java.
If you look at Twitter's Direct Message Endpoint you will see that it does not currently provide a way to "attach" an image when sending a direct message.
This has been confirmed at Twitter Developers forums before:
We have no announced plans yet for providing a media upload endpoint
for direct messages.
I have found a way to attach an image to a DM that works for me in my java project, using the following code:
...
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
//Get the User ID from the Screen Name
User user = twitter.showUser("screenName"); //#Hec_KuFlow for example
long userId = user.getId();
//The message to send
String message = "Hi! this is the message";
//Upload the file and get the ID
File imageFile = new File("C:\\demo\\picture.png");
long[] mediaIds = new long[1];
UploadedMedia media = twitter.uploadMedia(imageFile);
mediaIds[0] = media.getMediaId();
DirectMessage directMessage = twitter.directMessages().sendDirectMessage(userId, message, mediaIds[0]) throws TwitterException;
...
Use following code to send an image with text
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
Configuration configuration = configurationBuilder.build();
Twitter twitter = new TwitterFactory(configuration).getInstance();
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
For details explanation check this tutorial.
public void tweetPicture(File file, String message) throws Exception {
try{
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file);
mTwitter.updateStatus(status);}
catch(TwitterException e){
Log.d("TAG", "Pic Uploading error" + e.getErrorMessage());
throw e;
}
}
OR you can refer this

login twitter using twitter4j api without opening user authentication page in android

i am using twitter4j api for logging on the twiter and post tweets.
i have also registered the app on https://dev.twitter.com/apps/new and got consumer key and secret.
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String url = requestToken.getAuthenticationURL();
browser = (WebView) findViewById(R.id.webView1_test);
browser.loadUrl(requestToken.getAuthenticationURL());
browser.getSettings().setJavaScriptEnabled(true);
this is the code i m using to login. but the problem is that this opens a user authentication form in webview that takes username and password . i want to avoid opening that webpage and give login in password programatically. please help regarding this issue.
I don't believe Twitter offers an API for user authentication; only a user authentication webpage. You can check out their API documentation here: https://dev.twitter.com/docs
I had the same problem and I found this tutorial really helpful, please check this:
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this, consumer, provider, prefs).execute(uri);
finish();
}
}

How to Integrate Twitter Oauth as like Facebook?

I am new to integrating Twitter. I have implemented Twitter in my application with this code:
// Create file
File picture = new File(APP_FILE_PATH + "/myAwesomeDrawing.png");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic("username", "password");
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, "Image Uploaded from My AndroidDrawing App...");
}
catch (IOException e) {
e.printStackTrace();
}
catch (TwitPicException e) {
e.printStackTrace();
}
// If we got a response back, print out response variables
if(tpResponse != null)
tpResponse.dumpVars();
All works fine here. But here I have to add the username and password programmatically. Is there any other way to use the Twitter integration as like Facebook OAuth to integration?
I need to know how Twitter OAuth is checked, and if the User is not login then it will ask for the username and password in its in built window.
If caguilar187's code link's are not enough, then here are few more links for code help:
http://blog.doityourselfandroid.com/2011/08/08/improved-twitter-oauth-android/
http://blog.doityourselfandroid.com/2011/02/13/guide-to-integrating-twitter-android-application/
http://marakana.com/forums/android/examples/312.html
Best suggested: http://android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application
One more suggest: http://automateddeveloper.blogspot.com/2011/06/android-twitter-oauth-authentication.html
Post on Twitter: http://www.londatiga.net/it/how-to-post-twitter-status-from-android/
GitHub Link: https://github.com/brione/Brion-Learns-OAuth
Hope below link help you:-
Below link show you how to generate key with Twitter and other social media
http://code.google.com/p/socialauth-android/wiki/Twitter
Now below link is source code where u find out source code
http://code.google.com/p/socialauth-android/downloads/list
here are a few they all use signpost to do it.
Signpost:
http://code.google.com/p/oauth-signpost/
Blogs
http://dev.bostone.us/2009/07/16/android-oauth-twitter-updates/#awp::2009/07/16/android-oauth-twitter-updates/
http://blog.copyninja.info/2010/09/android-oauth-authentication-with.html
http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost

When access to directmessage in twitter4j, an error shows "unable to parse '3577866941' as integer"

I have set the value of ACCESS_TOKEN,ACCESSTOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET which I got from dev.twitter but it crashes when the application runs.I use twitter4j-core-2.1.8-SNAPSHOT.jar as library.The code is given bellow.
public ResponseList<DirectMessage> dmList=null;
public static AccessToken token = new AccessToken(ACCESS_TOKEN, ACCESSTOKEN_SECRET);
TwitterFactory factory = new TwitterFactory();
twitter = factory.getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(token);
try {
dmList = twitter.getDirectMessages(new Paging(1,15));
} catch (TwitterException e) {
e.printStackTrace();
}
Thanks.
Twitter userID and tweetID are not 32 bit integers. They recently upgraded them to 64bit, maybe your library is out of date ?

android twitter retrieveRequestToken 401 on request token

I am trying the following sample app for twitter oauth.
http://www.androidsdkforum.com/android-sdk-development/3-oauth-twitter.html
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
When i run the following code it gives exception as following
"oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match."
on this line String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
I provided the correct 'key' and 'secret' does twitter giving me wrong key and secret ?
I have spent several hours on this. Seems that you have to set ANY value to the callback url in the Settings tab in your Twitter application developer panel. Keeping the default empty value disables dynamic callback urls.
All the tutorials and all the information I have found online is just void. Twitter long removed the "Client / Website" radio button.
Moreover, OAuth checks for clock skews.
I just had the same problem. It only appeared on my dev phone, but on the emulator and another phone the code worked fine. After trying out several solutions to related questions with no luck, eventually it turned out that I had not set the time and date on the dev phone, which doesn't have a sim-card in it. This caused SSL certificates to be invalid and OAuth request to fail, as well as anything else that used HTTPS. After setting the time the problems went away.
**1) **Set date and time to the right values,
this will help to fix this issue.****
2)
private OAuthConsumer consumer;
private OAuthProvider provider;
...
...
...
provider = new CommonsHttpOAuthProvider (
TWITTER_REQUEST_TOKEN_URL,
TWITTER_ACCESS_TOKEN_URL,
TWITTER_AUTHORIZE_URL);
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token",
"http://twitter.com/oauth/authorize");
provider.setOAuth10a(true);
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Log.e(APP, e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
3) is your twitter app configured as Browser?
try with this keys:
Consumer key
sdOjEI2cOxzTLHMCCMmuQ
Consumer secret
biI3oxIBX2QMzUIVaW1wVAXygbynuS80pqSliSDTc
using https in place of http in provider
finally done, check out the following post
android twitter outh tutorial callback problem
yes totramon is right...If you are facing problem only while authentication problem , you may have to set device time. I was facing the same problem and solved with this solution only. Also if you are using old twitter api , you need to change it to stable version api(2.1.4). You can find from the following link :
http://twitter4j.org/en/index.html
Enjoy..

Categories

Resources