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();
}
}
Related
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
Bitmap bitmap1 = getFacebookProfilePicture(user.getId());
imgview.setImageBitmap(bitmap1);
} else {
userName.setText("You are not logged");
}
}
});
public Bitmap getFacebookProfilePicture(String userID) {
try {
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection()
.getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
This is my code i am trying to get Profile pic from Facebook and display it on image-view in my app i am able to get name from Facebook but when i put code for get Profile pic then i am unable to get image in android please tell me where am doing wrong give me solution how to set this code .
Use this method to get Bitmap from Url.
/**
* Download image from server url and return bitmap
*
* #param stringUrl Imaage download url
* #return Bitmap receieved from server
*/
private Bitmap downloadImage(String stringUrl) {
URL url;
Bitmap bm = null;
try {
url = new URL(stringUrl);
URLConnection ucon = url.openConnection();
InputStream is;
if (ucon instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) ucon;
int statusCode = httpConn.getResponseCode();
if (statusCode == 200) {
is = httpConn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
BufferedInputStream bis = new BufferedInputStream(is, 8192);
ByteArrayBuffer baf = new ByteArrayBuffer(1024);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
byte[] rawImage = baf.toByteArray();
bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
bis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
Pass Facebook Profile pic url to this method like this and set downloaded bitmap to imageview.
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
imgview.setImageBitmap(downloadImage(imageURL));
I hope it helps!
Use callbacks, they are much easier.
Create a callback as follows;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
if(jsonObject != null){
try {
String name = jsonObject.getString("name");
String email = jsonObject.getString("email");
String id = jsonObject.getString("id");
saveCurrentProfileInfo(id, name, email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, email, name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
createSnackBar("Facebook login cancelled");
}
#Override
public void onError(FacebookException e) {
createSnackBar("Error logging in to Facebook");
}
};
Then on your oncreate method, initialize a CallbackManager
CallbackManager callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, callback);
You can then use the id retrieved to get the profile picture like you did.
Assuming you got the right access tokens, The updated API shows picture field in JSON like this:
{
"id": "8169595750129122",
"name": "A user name",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xtp1/v/t1.0-1/p50x50/11150668_881451758563505_2749775492727269008_n.jpg?oh=35239d96bf3a6d34bd455c51218412d9&oe=56487861&__gda__=1446869670_cd2511b71fc9b8809d6b52bdbb451ff0"
}
}
}
If you want to get the picture url for example after logging in
LoginButton login_button = (LoginButton) view.findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
login_button.setFragment(this);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
//THIS CONTAINS the URL String displaying it is up to you
String PROFPIC_URL = object.getJSONObject("picture").getJSONObject("data").getString("url");
String FIRSTNAME = object.getString("first_name");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,picture,last_name,first_name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
textview.setText("Facebook Login Cancelled");
}
#Override
public void onError(FacebookException exception) {
textview.setText("Facebook Login Error");
}
});
You can do values experiments in here https://developers.facebook.com/tools/explorer/
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
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).
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
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();
}
});
}
}