Android image tweet - android

I m trying to tweet image from sd card folder but still can't do that. I m using twitter4j-core-3.0.3 api and gave permissions android.permission.INTERNET,android.permission.ACCESS_NETWORK_STATE. Here is my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
twitterButton = (Button) findViewById(R.id.twitPic);
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
new ImageSender().execute();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
// Get the access token
accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
private class ImageSender extends AsyncTask<URL, Integer, Long> {
private String url;
protected void onPreExecute() {
pDialog = ProgressDialog.show(MainActivity.this, "", "Sending image...", true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Long doInBackground(URL... urls) {
long result = 0;
Log.d(TAG, "Start sending image...");
try {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Friends/"+"image4.jpg";
File targetDirector = new File(targetPath);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate status = new StatusUpdate("");
status.setMedia(targetDirector);
twitter.updateStatus(status);
result = 1;
Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (TwitterException e) {
Log.e(TAG, "Failed to send image "+e);
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
pDialog.cancel();
String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
Here is my log
04-02 06:38:02.275: E/Tag(1762): Failed to send image 400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
04-02 06:38:02.275: E/Tag(1762): message - Bad Authentication data
04-02 06:38:02.275: E/Tag(1762): code - 215
04-02 06:38:02.275: E/Tag(1762): Relevant discussions can be found on the Internet at:
04-02 06:38:02.275: E/Tag(1762): http://www.google.co.jp/search?q=b2b52c28 or
04-02 06:38:02.275: E/Tag(1762): http://www.google.co.jp/search?q=11331d43
04-02 06:38:02.275: E/Tag(1762): TwitterException{exceptionCode=[b2b52c28-11331d43], statusCode=400, message=Bad Authentication data, code=215, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
Edit: When i try to tweet a text in this portion
StatusUpdate status = new StatusUpdate("");
status.setMedia(targetDirector);
twitter.updateStatus(status);
to twitter.updateStatus("If you're reading this on Twitter, it worked!"); then same error creates.
I m on it from some days but get no solution. Please anyone help me to solve the problem.Thanks

change you AsyncTask use like this it is working for me
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String status = null;
new updateTwitterStatus().execute(status);
}
});
public class updateTwitterStatus extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar_show();
}
protected String doInBackground(String... args) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
access_token = SharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
access_token_secret = SharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
String upload_image_url = postPicture( "/mnt/sdcard/yourimage.jpg", " ");
Log.d("--------------upload_image_url=" + upload_image_url.toString() + "---------", " ");
} catch (Exception e) {
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
public String postPicture(String fileName, String message) {
try {
Log.d("----start---postPicture()---", " ");
File file = new File(fileName);
MediaProvider mProvider = getMediaProvider();
String accessTokenToken = access_token;
String accessTokenSecret = access_token_secret;
Properties props = new Properties();
props.put(PropertyConfiguration.MEDIA_PROVIDER, mProvider);
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN, accessTokenToken);
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN_SECRET, accessTokenSecret);
props.put(PropertyConfiguration.OAUTH_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
props.put(PropertyConfiguration.OAUTH_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
Configuration conf = new PropertyConfiguration(props);
ImageUploadFactory factory = new ImageUploadFactory(conf);
ImageUpload upload = factory.getInstance(mProvider);
String url;
url = upload.upload(file, message);
Log.d("----end---postPicture()---", " ");
return url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
MediaProvider getMediaProvider() {
Log.d("----start---getMediaProvider()---", " ");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String provider = preferences.getString("pictureService", "twitter");
MediaProvider mProvider;
if (provider.equals("yfrog"))
mProvider = MediaProvider.YFROG;
else if (provider.equals("twitpic"))
mProvider = MediaProvider.TWITPIC;
else if (provider.equals("twitter"))
mProvider = MediaProvider.TWITTER;
else
throw new IllegalArgumentException("Picture provider " + provider + " unknown");
Log.d("----end---getMediaProvider()---", " ");
return mProvider;
}
protected void onPostExecute(String file_url) {
ProgressBar_hide();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT).show();
}
});
}
}

Related

Amazon Cognito Invalid login token Android

private Response.Listener<JSONObject> awsCognitoResponseListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
bar.setProgress(50);
Log.d("awsCognito Response:", jsonObject.toString());
try {
strIdentityPoolID = jsonObject.getString("IdentityPoolId");
identityID = jsonObject.getString("IdentityId");
strToken = jsonObject.getString("Token");
developerProviderName = jsonObject.getString("DeveloperProviderName");
// Toast.makeText(getActivity(), IdentityPoolId, Toast.LENGTH_SHORT).show();
File fileToUpload = new File(AppConstants.MAIN_DIRECTORY + File.separator + "Recordings" + "/" + chosenFile);
Log.v(TAG, fileToUpload.getPath());
Uri uri = Uri.fromFile(fileToUpload);
Log.v(TAG, uri.getPath());
HomeActivity parentActivity = (HomeActivity) getActivity();
/*Developer Authentication Access*/
AWSAsyncTask mAwsAsyncTask = new AWSAsyncTask();
mAwsAsyncTask.execute();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private class AWSAsyncTask extends AsyncTask<Void, String, String>
{
private String errorResponse;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
PutObjectResult putResponse = null;
CognitoParams cognitoParams = new CognitoParams();
cognitoParams.setIdentityPoolId(strIdentityPoolID);
cognitoParams.setIdentityId(identityID);
cognitoParams.setDeveloperProviderName(developerProviderName);
cognitoParams.setRegions(getRegion());
DeveloperAuthenticationProvider developerProvider = new DeveloperAuthenticationProvider(null, getActivity(), cognitoParams);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(getActivity(),developerProvider,getRegion());
Map<String, String> logins = credentialsProvider.getLogins();
if (logins == null)
{
logins = new HashMap<String, String>();
}
logins.put(AppConstants.DEVELOPER_PROVIDER, strToken.trim());
credentialsProvider.setLogins(logins);
try
{
AmazonS3Client s3Client = new AmazonS3Client(credentialsProvider);
File fileToUpload = new File(AppConstants.MAIN_DIRECTORY + File.separator + "Recordings" + "/" + chosenFile);
s3Client.setRegion(Region.getRegion(getRegion()));
PutObjectRequest putRequest = new PutObjectRequest(BucketName, S3FileName, fileToUpload);
putResponse = s3Client.putObject(putRequest);
Log.v("Response bimal: ", putResponse.toString());
return putResponse.toString();
}
catch (NotAuthorizedException e)
{
Log.e(TAG, e.getErrorMessage());
errorResponse = e.getErrorMessage();
}
catch (InvalidIdentityPoolConfigurationException e)
{
Log.e(TAG, e.getErrorMessage());
errorResponse = e.getErrorMessage();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
flag_btnClick = 1;
if (s != null)
{
uploadConfirmAPI();
}
else
{
errorDialog(errorResponse);
}
}
}
Developer Authenticated Identities
developer authenticated identities, you can register and authenticate users via your own existing authentication process, while still using Amazon Cognito to synchronize user data and access AWS resources Using developer authenticated identities involves interaction between the end user device, your backend for authentication, and Amazon Cognito but CognitoCachingCredentialsProvider not set token and identityID
In your DeveloperAuthenticationProvider you will need to call update(identityId, token).
You should also make sure that the token you are getting back from your back end server is not null.
Have you taken a look at the Cognito Sample that shows how to use Developer Authenticated Identities?:
https://github.com/awslabs/aws-sdk-android-samples/blob/master/CognitoSyncDemo/src/com/amazonaws/cognito/sync/demo/DeveloperAuthenticationProvider.java
Documentation:
http://docs.aws.amazon.com/cognito/latest/developerguide/developer-authenticated-identities.html

Uploading Video on Twitter

I am new to Twitter Integration with my Android Apps. I have to post Image and Video on Twitter. I am successfully able to post Image on Twitter using Twitpic, but have not found any clue for posting Video on the Twitter.
Please help me, with a relevant link or suggest me a method to do the same.
Sry for asking such a direct question without any piece of code..
You can upload media in TwitPic. This code is for image but in same manner you can upload video as well.
class ImageSender extends AsyncTask<URL, Integer, Long> {
private String url;
protected void onPreExecute() {
//mProgressDialog = ProgressDialog.show(SendImageActivity.this, "", "Sending image...", true);
//mProgressDialog.setCancelable(false);
//mProgressDialog.show();
}
protected Long doInBackground(URL... urls) {
long result = 0;
// TwitterSession twitterSession = new TwitterSession(SendImageActivity.this);
AccessToken accessToken = getAccessToken();
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(Constants.CONSUMER_KEY)
.setOAuthConsumerSecret(Constants.CONSUMER_SECRET)
.setOAuthAccessToken(mToken)
.setOAuthAccessTokenSecret(mSecreat)
.build();
OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));
ImageUpload upload = ImageUpload.getTwitpicUploader ("8d012dd3948af2cdc42f93859908a717", auth);
Log.d(TAG, "Start sending image...");
try {
url = upload.upload(new File(imagePath));
result = 1;
Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (Exception e) {
Log.e(TAG, "Failed to send image");
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
//mProgressDialog.cancel();
String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
System.out.println("Twitter Image==========="+text);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
public AccessToken getAccessToken() {
String token = mToken;
String tokenSecret = mSecreat;
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
Don't forgot to do login code first and using libraries(jars).

TwitterException: when uploading image to twitpic in android

I need to upload image to twitpic. In my sd card directory there are some images and i have to upload these to twitpic. Now i want to upload one image from them. Here is my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getApplicationContext().getSharedPreferences(
"MyPref", 0);
editor = sharedPref.edit();
uploadImage = (Button) findViewById(R.id.uploadImage);
uploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
new ImageSender().execute();
}
});
uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
oAuthAccessToken = twitter.getOAuthAccessToken(
verifier);
editor.putString(PREF_KEY_OAUTH_TOKEN, oAuthAccessToken.getToken());
editor.putString(PREF_KEY_OAUTH_SECRET,
oAuthAccessToken.getTokenSecret());
editor.commit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private class ImageSender extends AsyncTask<URL, Integer, Long> {
private String url;
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this, "", "Sending image...", true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
protected Long doInBackground(URL... urls) {
long result = 0;
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(twitter_consumer_key)
.setOAuthConsumerSecret(twitter_secret_key)
.setOAuthAccessToken(sharedPref.getString(OAuth.OAUTH_TOKEN, ""))
.setOAuthAccessTokenSecret(sharedPref.getString(OAuth.OAUTH_TOKEN_SECRET, ""))
.build();
OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));
ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth);
Log.d(TAG, "Start sending image...");
try {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Friends/"+"image4.jpg";
File targetDirector = new File(targetPath);
url = upload.upload(new File(targetDirector.getAbsolutePath()));
result = 1;
Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (Exception e) {
Log.e(TAG, "Failed to send image "+e);
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
mProgressDialog.cancel();
String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
In the following portion of my code i am getting a message in my log
try {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Friends/"+"image4.jpg";
File targetDirector = new File(targetPath);
url = upload.upload(new File(targetDirector.getAbsolutePath()));
result = 1;
Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (Exception e) {
Log.e(TAG, "Failed to send image "+e);
e.printStackTrace();
}
Here is my log
04-01 05:32:39.394: E/Tag(1438): Failed to send image Write error: ssl=0x2a19e750: I/O error during system call, Broken pipeTwitterException{exceptionCode=[f69e96cd-132d5002 883a7a68-527cabed], statusCode=-1, retryAfter=0, rateLimitStatus=null, version=2.1.6}
How can i solve the problem? Thanks

How to upload photo in user twitter profile in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we post image on twitter using twitter API in Android?
Android twitter tweet with image
i have to take picture from the camera and upload in user tweet status.I am unable to do please help. I have used followig code to post text but unable to upload photo in bitmap to twiiter
public void shareTwitter()
{
try {
String token = myPrefs.getString(FindFriends.PREF_KEY_OAUTH_TOKEN, "");
String secret = myPrefs.getString(FindFriends.PREF_KEY_OAUTH_SECRET, "");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(FindFriends.TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(FindFriends.TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(token)
.setOAuthAccessTokenSecret(secret);
AccessToken accessToken = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory(cb.build()).getInstance(accessToken);
twitter.updateStatus("hello");
} catch (Exception e) {
e.printStackTrace();
try this code hope this will You.
Twitter twitter = new TwitterFactory(conf).getInstance();
Bitmap bmp = BitmapFactory.decodeResource(
TwitterFriends.this.getResources(), R.drawable.edit_ic);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
StatusUpdate status = new StatusUpdate(message);
status.setMedia("newyear", bis);
try {
twitter.updateStatus(status);
} catch (Exception e) {
e.printStackTrace();
}
Twitter will update just status and not pictures. If you want to achieve then search for uploading images to TwitPic which will give you an bit.ly url of your image on TwitPic. Post the same url on Twitter which will redirect the user to Picture.
this is the upload button...
upload.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
new ImageSender().execute();
}
});
and this is Async Task...
private class ImageSender extends AsyncTask<URL, Integer, Long>
{
private String url;
protected void onPreExecute()
{
//mProgressDialog = ProgressDialog.show(SendImageActivity.this, "", "Sending image...", true);
//mProgressDialog.setCancelable(false);
//mProgressDialog.show();
}
protected Long doInBackground(URL... urls)
{
long result = 0;
prefs = PreferenceManager.getDefaultSharedPreferences(TestingTwitterActivity.this);
String token1=prefs.getString("token", null);
String tokenSecret1=prefs.getString("tokenSecret", null);
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(twitter_consumer_key)
.setOAuthConsumerSecret(twitter_secret_key)
.setOAuthAccessToken(token1)
.setOAuthAccessTokenSecret(tokenSecret1)
.build();
OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));
ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth);
//Log.d(TAG, "Start sending image...");
try {
url = upload.upload(new File(mPath));//here your camera pic file path...
result = 1;
//Log.d(TAG, "Image uploaded, Twitpic url is " + url);
} catch (Exception e) {
//Log.e(TAG, "Failed to send image");
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Long result)
{
//mProgressDialog.cancel();
String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}

Getting Exception while Integrating twitter in android

I have Written the code to Integrate the Twitter in android.In that I am getting the first scrren and when I am writing some message to twitt and click on the twitt button I am getting following Exception as OauthCommunication Exception communication with the service provider failed.I have entered the Consumer key Consumer secrete properly.
Public class MainActivity extends Activity {
private static final String TAG = "TwitterDemo";
private static final String CONSUMER_KEY = "xxx";
private static final String CONSUMER_SECRET = "xxx";
private static final String CALLBACK_SCHEME = "twitter-OAUTH-test-app";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
private static final String TWITTER_USER = "androidtestacc1#gmail.com";
private OAuthSignpostClient oauthClient;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private Twitter twitter;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mProvider = new DefaultOAuthProvider(
"http://api.twitter.com/oauth/request_token",
"http://api.twitter.com/oauth/access_token",
"http://api.twitter.com/oauth/authorize");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String token = prefs.getString("token", null);
String tokenSecret = prefs.getString("tokenSecret", null);
if (token != null && tokenSecret != null) {
mConsumer.setTokenWithSecret(token, tokenSecret);
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(TWITTER_USER, oauthClient);
} else {
Log.d(TAG, "onCreate. Not Authenticated Yet " );
new OAuthAuthorizeTask().execute();
}
}
class OAuthAuthorizeTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String authUrl;
String message = null;
Log.d(TAG, "OAuthAuthorizeTask mConsumer: " + mConsumer);
Log.d(TAG, "OAuthAuthorizeTask mProvider: " + mProvider);
try {
authUrl = mProvider.retrieveRequestToken(mConsumer,
CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(authUrl));
startActivity(intent);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
public void tweet(View view) {
if (twitter == null) {
Toast.makeText(this, "Authenticate first", Toast.LENGTH_LONG)
.show();
return;
}
EditText status = (EditText) findViewById(R.id.editTextTweet);
new PostStatusTask().execute(status.getText().toString());
}
class PostStatusTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
twitter.setStatus(params[0]);
return "Successfully posted: " + params[0];
} catch (TwitterException e) {
e.printStackTrace();
return "Error connecting to server.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
/* Responsible for retrieving access tokens from twitter */
class RetrieveAccessTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String message = null;
String oauthVerifier = params[0];
try {
// Get the token
Log.d(TAG, " RetrieveAccessTokenTask mConsumer: " + mConsumer);
Log.d(TAG, " RetrieveAccessTokenTask mProvider: " + mProvider);
Log.d(TAG, " RetrieveAccessTokenTask verifier: " + oauthVerifier);
mProvider.retrieveAccessToken(mConsumer, oauthVerifier);
String token = mConsumer.getToken();
String tokenSecret = mConsumer.getTokenSecret();
mConsumer.setTokenWithSecret(token, tokenSecret);
Log.d(TAG, String.format(
"verifier: %s, token: %s, tokenSecret: %s", oauthVerifier,
token, tokenSecret));
// Store token in prefs
prefs.edit().putString("token", token)
.putString("tokenSecret", tokenSecret).commit();
// Make a Twitter object
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(null, oauthClient);
Log.d(TAG, "token: " + token);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
/*
* Callback once we are done with the authorization of this app with
* Twitter.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "intent: " + intent);
// Check if this is a callback from OAuth
Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(CALLBACK_SCHEME)) {
Log.d(TAG, "callback: " + uri.getPath());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, "verifier: " + verifier);
Log.d(TAG, " xxxxxxxxxxx mConsumer access token: " + mConsumer.getToken());
Log.d(TAG, " xxxxxxxxxxxx mConsumer access token secret: " + mConsumer.getTokenSecret());
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN: " + OAuth.OAUTH_TOKEN);
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN_SECRET: " + OAuth.OAUTH_TOKEN_SECRET);
new RetrieveAccessTokenTask().execute(verifier);
}
}
public void logout(View view){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("token", null);
editor.putString("tokenSecret", null);
editor.commit();
finish();
}
}
error
10-19 15:18:55.424: W/System.err(995): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
10-19 15:18:55.424: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
10-19 15:18:55.438: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
10-19 15:18:55.655: W/System.err(995): ... 9 more
try another way to integerate twitter in your app
Using auth & webview(Twitter4j library)
http://davidcrowley.me/?p=410
http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/
code(url open in web view)
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
System.out.println("requesttoken"+requestToken);
} catch (TwitterException e) {
e.printStackTrace();
}
twitterUrl = requestToken.getAuthorizationURL();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN);
builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET);
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
twitter = new TwitterFactory().getInstance(auth);
try {
twitter.updateStatus("Hello World!");
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
}
2. On Button Click(Without auth)
String message="";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));
startActivity(i);
Please put following permission in your Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
also check this link....
http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application

Categories

Resources