Uploading Video on Twitter - android

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).

Related

Not able to retrieve profile pic with fb login

I followed the tutorial of facebook on their official page:
Facebook Login tutorial
However, after I finished this I do can login, but it doesn't retrieve my profile picture. Anyone else experienced this or has an idea what might cause this? I am getting no errors whatsoever..
I think you are clear upto getting facebook useUserId and FacebookToken.
Profile picture get can be done in two ways:
1: Facebook has provided you a view for profile picture `ie ProfilePictureView
in place of imageview in xml layout file take this view.
At the time of loadng image in this view simply do
ProfilePictureView profilePictureView;
profilePictureView = (ProfilePictureView) findViewById(R.id.friendProfilePicture);
profilePictureView.setCropped(true);
profilePictureView.setProfileId(USER_ID);
2: Another Option is get profile picture with the help of facebook token
ImageView imgProfilePic12=(ImageView)findViewById(R.id.imgProfilePic);
new LoadProfileImage(imgProfilePic12)
.execute("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="
+ Faceboo_Access_Token);
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
have you successfully logged in Facebook ?
if yes then
try {
JSONObject fbResObj = new JSONObject(fbUser
.getInnerJSONObject().toString());
String id = fbResObj.getString("id");
url = new URL("http://graph.facebook.com/" + id
+ "/picture?style=small");
Log.v(TAG, url.toString());
bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
try this , where fbUser is the object of GraphUser which u get on executing GraphUserCallBack,
private void getUserDetail() {
String fqlQuery = "SELECT name,uid,pic FROM user WHERE uid in (SELECT uid1 FROM friend WHERE uid1=me())";
Bundle _params = new Bundle();
_params.putString("q", fqlQuery);
Session _session = Session.getActiveSession();
Request _request = new Request(_session, "/fql", _params, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
if (graphObject.getProperty("data") != null) {
try {
String _arry = graphObject.getProperty("data").toString();
JSONArray _jsonArray = new JSONArray(_arry);
if(_jsonArray.length()==1)
{
//here u will get your user's userId and Profile Picture and Name
String _uid = _jsonObject.getString("uid");
String _Name = _jsonObject.getString("name");
String _ImagePath = _jsonObject.getString("pic");
}
}
} catch (JSONException ex) {
if (ex != null) {
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
}
});
Request.executeBatchAsync(_request);
}
If you have Facebook id of user to get image use this link
https://graph.facebook.com/FACEBOOK_USER_ID/picture?type=large";
for small image use type = small

Share image by url in twitter

This is code
StatusUpdate status = new StatusUpdate(msg);
twitter.updateStatus(status);
it work fine.
but i want share my image by url
please help me.
Try following :
Get the path of the image you wish to upload, if it is already on sd-card. If not then download it first, save to sd card and then get the path.
Then create a file using that filepath (picFilePath) as follows :
File imgFile = new File(picFilePath);
Set this file as media in statusupdate object,
// the txt message
StatusUpdate status = new StatusUpdate(Msg);
// set the image file as media with the message.
status.setMedia(imgFile);
Upload the message with image using an AsyncTask
twitter.updateStatus(status);
Hope this helps you.
try this:
T4JTwitterFunctions.postToTwitter
(your_class.this.getApplicationContext(),your_class.this, twitter_consumer_key, twitter_consumer_secret,
Your_URL, new T4JTwitterFunctions.TwitterPostResponse()
{ #Override public void OnResult(Boolean success)
{
if(success)
{
//success
}
else
{
//not success
}
}
});
you can do this with the help of the twitPic4j API. Just add the API for twitPic4j and write below code to upload the photo.
first you have to download the picture from url, save it to temp folder then upload it and after uploading delete this temporary image.
File picture = new File(APP_FILE_PATH + "/"+filename+".jpg");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic(TWITTER_NAME, TWITTER_PASSWORD);
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, customMessageEditText.getText()+" http://www.twsbi.com/");
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please enter valid username and password.", Toast.LENGTH_SHORT).show();
}
catch (TwitPicException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Invalid username and password.", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please enter valid Username and Password.", Toast.LENGTH_SHORT).show();
}
// If we got a response back, print out response variables
if(tpResponse != null) {
tpResponse.dumpVars();
System.out.println(tpResponse.getStatus());
if(tpResponse.getStatus().equals("ok")){
Toast.makeText(getApplicationContext(), "Photo posted on Twitter.",Toast.LENGTH_SHORT).show();
//picture.delete();
}
}
I think this code will help you:
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
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, "");
System.out.println(access_token+access_token_secret+"....."+PREF_KEY_OAUTH_TOKEN);
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate ad=new StatusUpdate("mala ruparel...........");
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = getResources().openRawResource(R.drawable.f1);
ad.setMedia("Malvika",is);
// Update status
twitter4j.Status response = twitter.updateStatus(ad);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}

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

Android image tweet

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();
}
});
}
}

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();
}
}

Categories

Resources