Android twitter tweet with image [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we post image on twitter using twitter API in Android?
I am working in an android application and I want to tweet a message and a picture to twitter. I am able to tweet only tweets to twitter by the code :
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
**twitter.updateStatus("New tweet");**
twitter.//Which property of twitter should I use to tweet an image and //message
} catch (TwitterException e) {
// TODO Auto-generated catch block
Log.e("Errorssssssssssssss", e.toString());
}
How do I include an image as well?

refer to http://www.londatiga.net/it/how-to-post-twitter-status-from-android/, use twitter4j library
public void uploadPic(File file, String message) throws Exception {
try{
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file);
mTwitter.updateStatus(status);}
catch(TwitterException e){
Log.d("TAG", "Pic Upload error" + e.getErrorMessage());
throw e;
}
}
where mTwitter is an instance of Twitter class
Make sure you are using latest version of twitter4j-core jar file.

U can try example which comes with Twitter4j Library.Following code will help u
public final class TwitpicImageUpload {
/**
* Usage: java twitter4j.examples.media.TwitpicImageUpload [API key] [message]
*
* #param args message
*/
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java twitter4j.examples.media.TwitpicImageUpload [API key] [image file path] [message]");
System.exit(-1);
}
try {
Configuration conf = new ConfigurationBuilder().setMediaProviderAPIKey(args[0]).build();
ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);
String url;
if (args.length >= 3) {
url = upload.upload(new File(args[1]), args[2]);
} else {
url = upload.upload(new File(args[1]));
}
System.out.println("Successfully uploaded image to Twitpic at " + url);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to upload the image: " + te.getMessage());
System.exit(-1);
}
}
}
Download Twitter4j Library look for more examples there.

Related

How to upload media to twitter from background of application without showing any UI to user except login screen once?

I have tried to visit twitter developer website
but i was not getting proper answer from there as i tried different ways to solve this problem but i did found TweetComposer.Builder still i was not able to work with it.
i have found solution for my question i have downloaded and integrated a library from here with the help of this library i am able to post multiple media
Step 1:
first login to twitter by integrating library from this link according to guidance
Step 2:
After that you will be able to login with twitter and you will get two things 1)authToken.token and 2)authToken.secret store this for further use.
Step 3:
public void updateTwitterStatus() {
new AsyncTask() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] params) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(getResources().getString("YOUR_TWITTER_CONSUMER_KEY"));
builder.setOAuthConsumerSecret(getResources().getString("YOUR_TWITTER_CONSUMER_SECRET"));
// Access Token
String access_token = sharedPreferences.getString("authToken.token", "");
// Access Token Secret
String access_token_secret = sharedPreferences.getString("authToken.secret", "");
twitter4j.auth.AccessToken accessToken = new twitter4j.auth.AccessToken(access_token, access_token_secret);
twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status for single image upload with raw folder
StatusUpdate statusUpdate = new StatusUpdate("posted from my app");
InputStream is = getResources().openRawResource(R.raw.lakeside_view);
statusUpdate.setMedia("test.jpg", is);
// Update status for single image upload with file
/*String statusMessage = "posted from my app";
StatusUpdate statusUpdate = new StatusUpdate(statusMessage);
statusUpdate.setMedia(file);*/
// Update status for multiple images upload with file
/*String statusMessage = "Hey I am posting 2 images of xyz event";
File imagefile1 = new File(Environment.getExternalStorageDirectory()+"/images/image_1.jpg");
File imagefile2 = new File(Environment.getExternalStorageDirectory()+"/images/image_2.jpg");
long[] mediaIds = new long[2];
UploadedMedia media1 = twitter.uploadMedia(imagefile1);
mediaIds[0] = media1.getMediaId();
UploadedMedia media2 = twitter.uploadMedia(imagefile2);
mediaIds[1] = media2.getMediaId();
StatusUpdate statusUpdate = new StatusUpdate(statusMessage);
statusUpdate.setMediaIds(mediaIds);*/
// to post twit
twitter4j.Status response = twitter.updateStatus(statusUpdate);
Log.d("Status", response.getText());
} catch (twitter4j.TwitterException e) {
Log.d("Failed to post!", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Object o) {
*//* Dismiss the progress dialog after sharing *//*
Toast.makeText(getApplicationContext(), "Posted to Twitter!", Toast.LENGTH_SHORT).show();
super.onPostExecute(o);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
i have tried this code it works for me.

Upload audio url in twitter android

i am stuck in Twitter integration.I am done with image uploading through url but i am not able to upload audio or video url to twitter.
Any help is appreciated. Thanx guys
Twitter Code for uploading youtube url:
twitter.updateStatus("This is My Youtube url Test http://youtu.be/pfHxl46KyZM");
Logcat:
403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - Error creating status.
code - 189
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=12c480e1
TwitterException{exceptionCode=[b2b52c28-12c480e1], statusCode=403, message=Error creating status., code=189, retryAfter=-1, rateLimitStatus=null, version=3.0.6-SNAPSHOT}
String tweetUrl = "https://twitter.com/intent/tweet?text=Put your Audio URL here &url="
+ "https://www.google.com&hashtags=android,twitter";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
OR
// Consumer
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// Access Token
AccessToken accessToken = null;
accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_SECRET);
twitter.setOAuthAccessToken(accessToken);
// Posting Status
Status status = null;
try {
status = twitter.updateStatus("YOUR_AUDIO_LINK");
} catch (TwitterException e) {
e.printStackTrace();
}
System.out.println("Successfully updated the URL: "
+ status.getText());
You cannot upload video directly to Twitter - they simply don't support it.
Follow these steps.
1.Upload the video to a 3rd party service (like YouTube)
2.Get the public URL of the uploaded video
3.Add the URL to the status you send to Twitter - e.g. "Look at my Birtday video http://youtube.com/id"
If you want, you can add a thumbnail of the video as an image attachment
Hope this is what you are looking for.
Note sure but check if this helps you:-
String videoPath="video file path";
TwitterSession twitterSession = new TwitterSession(MainActivity.this);
AccessToken accessToken = twitterSession.getAccessToken();
Values values = new Values();
values.setSession(new Session());
TwitvidApi api = new TwitvidApi(values);
api.setSecureUrlEnabled(false);
Session session;
try {
session = api.authenticate(new TwitterAuthPack.Builder()
.setConsumerKey(twitter_consumer_key)
.setConsumerSecret(twitter_secret_key)
.setOAuthToken(accessToken.getToken())
.setOAuthTokenSecret(accessToken.getTokenSecret()).build());
api.getValues().setSession(session);
final UploadHelper helper = new UploadHelper(api);
File file = new File(videoPath);
TwitvidPost twitvidPost = new TwitvidPost.Builder().setFile(file)
.setChunkSize(10485760).setMessage("Twitvid test")
.setPostToTwitter(true).create();
try {
if (helper.upload(twitvidPost)) {
Toast.makeText(MainActivity.this, "Posted on Twitter and Twitvid" ,Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Posted on Twitter and Twitvid");
} else {
Toast.makeText(MainActivity.this, "Post failed", Toast.LENGTH_LONG)
.show();
Log.d("MainActivity", "Posted failed");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ApiException e1) {
e1.printStackTrace();
}

Android, Twitter4j, REST 1.1 - How do I finish the OAuth Process?

I have been at this since the weekend and I am at an impasse. I am pretty new to programming and suspect I am in over my head because I have read every link under "Similar Questions" and it either does not apply or confuses me more.
I am using the Twitter4j API and I worked from code sample no. 7 on the twitter4j website on OAuth support at http://twitter4j.org/en/code-examples.html.
As a skill-building project, I want to make an Android celebrity fan app that will download the timeline from the celebrity's public account. The goal is to execute a timeline download of all the tweets. I do not want the user to login to Twitter with this app or post tweets. The app just downloads a timeline in the background and displays the tweets, probably in a list view.
My code is not executing the following line. It seems to just hang there waiting for something to happen.
RequestToken requestToken = twitter.getOAuthRequestToken();
I have internet permissions in manifest. At this point, I am so confused, I do not even know if I have registered my app correctly. I have the four keys (consumer, consumer secret, access, and access secret).
Settings
-Website: made something up
-Application Type: Read Only
-Callback URL: left it blank
-I did not opt in to "Sign In With Twitter."
OAuth Tool
-Request Type: GET
-Request URI: https://api.twitter.com/1/ (probably wrong)
This is my code:
public class TwitterActivity extends Activity
{
Button mButtonTweets;
String JSONString = null;
TextView JSONContent;
class GetTwitterTimeline extends AsyncTask<Void, String, String>
{
#Override
protected String doInBackground(Void... params)
{
try
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try
{
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
while (accessToken == null)
{
onProgressUpdate(requestToken.getAuthenticationURL());
try
{
accessToken = twitter.getOAuthAccessToken();
}//try
catch(TwitterException te)
{
if (te.getStatusCode() == 401)
{
onProgressUpdate("Unable to get the access token");
}//if
else
{
te.printStackTrace();
}//else
}//catch
}//while
onProgressUpdate("Got Access Token");
onProgressUpdate("Access Token: " + accessToken.getToken());
onProgressUpdate("Access Token Secret: " + accessToken.getTokenSecret());
}//try
catch (IllegalStateException ie)
{
if(!twitter.getAuthorization().isEnabled())
{
onProgressUpdate("OAuth consumer key/secret is not set.");
}//if
}//catch
}//try
catch (TwitterException te)
{
te.printStackTrace();
onProgressUpdate("Failed to get timeline");
}//catch
String JSONString = "JSON content will go here";
return JSONString;
}//doInBackground
protected void onProgressUpdate(String logEntry)
{
Log.d("twitter4j", logEntry);
}
#Override
protected void onPostExecute(String jsonString)
{
JSONString = jsonString;
}
}//end inner class
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_twitter);
new GetTwitterTimeline().execute();
JSONContent = (TextView) findViewById(R.id.textview_tweets);
mButtonTweets = (Button) findViewById(R.id.button_tweets);
mButtonTweets.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
JSONContent.setText(JSONString);
}
});
}
}
Twitter API has been updated. So Request URI: https://api.twitter.com/1/ won't work.
Also AFAIK the way you are trying to make the app won't work out. You need some kind of authentication. I also dumped one of my app after this API change. :(
Read the following link:
https://dev.twitter.com/docs/api/1.1/overview

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

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

Gdata map Api in android

i am trying to implement gdata map api in my android project.. but i am unable to solve this error
"java.lang.VerifyError: com.google.gdata.client.media.MediaService"
i am using all the libraries required to implement gdata apis
MapsService myService = new MapsService("createMap"); error is coming due to this line
is there any clue..
thnx..
i am trying with following code
//
**MapsService myService = new MapsService("createMap");**
try {
// Replace username and password with your authentication credentials
myService.setUserCredentials("username","password");
createMap(myService);
} catch(AuthenticationException e) {
System.out.println("Authentication Exception");
} catch(ServiceException e) {
System.out.println("Service Exception: " + e.getMessage());
} catch(IOException e) {
System.out.println("I/O Exception");
}
}
public static MapEntry createMap(MapsService myService)
throws ServiceException, IOException {
// Replace the following URL with your metafeed's POST (Edit) URL
// Replace userID with appropriate values for your map
final URL editUrl = new URL("http://maps.google.com/maps/feeds/maps/userID/full");
MapFeed resultFeed = myService.getFeed(editUrl, MapFeed.class);
URL mapUrl = new URL(resultFeed.getEntryPostLink().getHref());
// Create a MapEntry object
MapEntry myEntry = new MapEntry();
myEntry.setTitle(new PlainTextConstruct("Demo Map"));
myEntry.setSummary(new PlainTextConstruct("Summary"));
myEntry.getAuthors().add(new Person("My Name", null, "username"));
return myService.insert(mapUrl, myEntry);
}
You have to add "servlet.jar, activation.jar, mail.jar" In your source code

Categories

Resources