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("");
}
});
}
}
Related
I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.
I have made an asynctask for getting some Json response from a webservice.I have used a progress bar when background processing done it displays,and have finished that progress Dialog in onPostExecute method of my asynctask.Thing is that i got successful response as per needed,But myl progress Dialog remains visible after that,Please can any one tell me how to dismiss it.My code is as below:
main.java
private class DoFavourite extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String favUrl = Const.API_DO_FAVOURITE + "?product_id=" + pid + "&customer_id=" + Pref.getValue(ProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "");
System.out.println(":::::::::my FAVOURITE URL::::::::::::::" + favUrl);
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(favUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_STATUS)) {
if (jsonObj.getString(Const.TAG_STATUS).equalsIgnoreCase("success")) {
if (jsonObj.getString(Const.TAG_FAVOURITE).equalsIgnoreCase("1")) {
flag = 1;
} else {
flag = 2;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
You are not using the progress dialog right. You'll notice the IDE shows a neat little warning sign next to your pd.show(...) line.
What you are doing is
Create an (invisible, irrelevant) progress dialog using new ProgressDialog()
Create another progress dialog with the desired text using pd.Show(), without storing a reference to it.
Dismiss the first dialog. The dialog from (2) remains.
If you replace your code with:
//pd = new ProgressDialog(this);
pd = ProgressDialog.show(this, "Waiting...", "Please wait five seconds...");
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 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();
}
});
}
}
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();
}
}