How to send an image as direct message with twitter in android? - android

I want to send an image with text to a follower using twitter4j. I am able to send a direct message like this:
twitter.sendDirectMessage(twitterID, message);
Now, I can't figure out how to send an image as direct message. I did this for posting a tweet, which works:
StatusUpdate status = new StatusUpdate(message);
status.setMedia(pathOfTheFileToSend);
twitter.updateStatus(status);
So is it possible to send a image as direct message in twitter with the library twitter4j?
Thanks in advance.

First it's worth noting what Twitter4j does. It provides a good abstraction and bindings to Twitter's REST API in Java.
If you look at Twitter's Direct Message Endpoint you will see that it does not currently provide a way to "attach" an image when sending a direct message.
This has been confirmed at Twitter Developers forums before:
We have no announced plans yet for providing a media upload endpoint
for direct messages.

I have found a way to attach an image to a DM that works for me in my java project, using the following code:
...
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
//Get the User ID from the Screen Name
User user = twitter.showUser("screenName"); //#Hec_KuFlow for example
long userId = user.getId();
//The message to send
String message = "Hi! this is the message";
//Upload the file and get the ID
File imageFile = new File("C:\\demo\\picture.png");
long[] mediaIds = new long[1];
UploadedMedia media = twitter.uploadMedia(imageFile);
mediaIds[0] = media.getMediaId();
DirectMessage directMessage = twitter.directMessages().sendDirectMessage(userId, message, mediaIds[0]) throws TwitterException;
...

Use following code to send an image with text
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
Configuration configuration = configurationBuilder.build();
Twitter twitter = new TwitterFactory(configuration).getInstance();
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
For details explanation check this tutorial.

public void tweetPicture(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 Uploading error" + e.getErrorMessage());
throw e;
}
}
OR you can refer this

Related

How to checkin in Twitter from Android application?

I am developing an android app and I want to share some text content via Twitter. User will just click one button and i will push a tweet like instagram and foursquare. I have done some search but all the examples requires user to click tweet button. I want to sende automatically in the background. I know the text already, user will just click a button. Is there any example for this.
Thank you already.
You could maybe use Twitter4J:
Setup the authentification:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*********************")
.setOAuthConsumerSecret("******************************************")
.setOAuthAccessToken("**************************************************")
.setOAuthAccessTokenSecret("******************************************");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Post a tweet:
Status status = tf.updateStatus("Hello World!");
It is possible to use
Twitter Rest API
https://docs.fabric.io/android/twitter/access-rest-api.html
E.g.,
https://docs.fabric.io/android/twitter/log-in-with-twitter.html#login-with-twitter
Sample code to retrieve token, secret:
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
Sample code to send a message:
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("just setting up my Fabric.")
.image(myImageUri);
builder.show();

Facebook SDK and sharing a Play Store app link with ShareDialog issue

I'm trying to share a link(my Google Play app link) using ShareDialog from Facebook SDK but the problem is that when the URL is my app's Google Play link the other information is not displayed correctly... Actually it's displaying only the link from Google Play without name or description!
Here's the code:
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
this)
.setLink("https://play.google.com/store/apps/details?id=<myapp>")
.setDescription("Test")
.setName("Test for facebook")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
I tried everything and with other URL's actually is working(displaying name, description, caption etc.) but not with the app's URL.
Does anyone know why a Google Play link won't work with text, description or caption?
Actually if you specify the contentUrl (as in 4.0) or link (as in your case), it overrides the name, description, etc. You just don't need to give other things as it then becomes responsibility of url host to supply the details that should be shown when it gets posted on Facebook timeline.
Although, if you want to share something like Message from user followed by your app link. Then I would suggest to go for Graph API (I wasted 2-3 days in posting something like this via ShareApi/ShareDialog but ended up with using Graph API only.)
Code to share using Graph API:
// Constants to be used when sharing message on facebook time line.
private static final int FACEBOOK_ERROR_PERMISSION = 200;
private static final String PARAM_EXPLICIT = "fb:explicitly_shared";
private static final String PARAM_GRAPH_PATH = "/me/feed";
private static final String PARAM_MSG = "message";
private static final String PARAM_LINK = "link";
// Create the parameter for share.
final Bundle params = new Bundle();
params.putBoolean(PARAM_EXPLICIT, true);
params.putString(PARAM_LINK, BirdingUtah.APP_URL);
// If message is empty, only our link gets posted.
String message = "This is the message to share";
if (!TextUtils.isEmpty(message))
params.putString(PARAM_MSG, message);
// Send the request via Graph API of facebook to post message on time line.
new GraphRequest(AccessToken.getCurrentAccessToken(), PARAM_GRAPH_PATH,
params, HttpMethod.POST, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
searchDialog.dismiss();
if (graphResponse.getError() == null) {
// Success in posting on time line.
Logger.toastShort(R.string.msg_share_success);
Logger.debug(TAG, "Success: " + graphResponse);
} else {
FacebookRequestError error = graphResponse.getError();
if (error.getErrorCode() == FACEBOOK_ERROR_PERMISSION)
// Cancelled while asking permission, show msg
Logger.toastLong(R.string.msg_share_permission);
else
// Error occurred while posting message.
Logger.toastShort(R.string.msg_share_error);
Logger.error(TAG, "Error: " + error);
}
// Enable the button back again if profile and access token are non null.
if (Profile.getCurrentProfile() != null || AccessToken.getCurrentAccessToken() != null)
mShareButton.setEnabled(true);
}
}).executeAsync();

How can I get a Twitter public timeline with no user authentication using Twitter4j?

I've wrote some code to allow a user to login to his Twitter account and send Tweet using Twitter4j and following this tutorial.
Now I can also get the tweets of a public account using
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setHttpConnectionTimeout(10000)
.setHttpReadTimeout(10000)
.setOAuthConsumerKey(Config.TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(Config.TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(Utils.getPrefsString(getActivity(),
TwitterPrefsFragment.PREF_KEY_OAUTH_TOKEN, "")) // empty if not authentified
.setOAuthAccessTokenSecret(Utils.getPrefsString(getActivity(),
TwitterPrefsFragment.PREF_KEY_OAUTH_SECRET, "")); // empty if not authentified
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<twitter4j.Status> statuses = twitter.getUserTimeline(SOME_PUBLIC_TWITTER_ACCOUNT, new Paging(1, 50));
but this only works when the user is authenticated and the app has the oauth token and secret in the preferences..
How can I get a Twitter public timeline with no Access Token, i.e. without having the user to authenticate?
EDIT
I'm reformulating my question to make it clearer:
I managed to authenticate my Twitter app and a user with the code given here.
Now, if the user is not logged in, how can I get a public timeline? In that case, there is no OAUTH_TOKEN and OAUTH_SECRET, and the request shown above does not work because an empty string is set to ConfigurationBuilder.setOAuthAccessToken and ConfigurationBuilder.setOAuthAccessTokenSecret.
So what is, if it exists, the request to get a public timeline, with no OAUTH_TOKEN and OAUTH_SECRET?
In your case, you should use Application-only authentication.
To do this with Twitter4J, try the following code
ConfigurationBuilder cb = new ConfigurationBuilder();
cb
.setOAuthConsumerKey(<YOUR_CONSUMER_KEY>)
.setOAuthConsumerSecret(<YOUR_CONSUMER_SECRET>)
.setApplicationOnlyAuthEnabled(true); // IMPORTANT: set T4J to use App-only auth
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
OAuth2Token token = twitter.getOAuth2Token();
if (token != null) {
System.out.println("Token Type : " + token.getTokenType());
System.out.println("Access Token: " + token.getAccessToken());
}
ResponseList<Status> list = twitter.getUserTimeline(783214); // Load #twitter's timeline without user login.
Key points of the above sample code:
Call setApplicationOnlyAuthEnabled(true) to enable Application-only authentication.
Get the access Token using getOAuth2Token() instead of getOAuthAccessToken()
This is certainly possible and I have already tried it. If your doubt is only regarding the Access Token and Access Token secret being empty, then you should try to use the Access Token provided in the app page. By app page I mean, the link where you have registered your twitter app.
If you go to dev.twitter.com ,and go to your app settings, you can see a consumer key, consumer secret, access token and access token secret. Make use of these and follow my below code and it should work,
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("B*************Q")
.setOAuthConsumerSecret(
"l*************o")
.setOAuthAccessToken(
"1*************s")
.setOAuthAccessTokenSecret(
"s*************s");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
try {
List<Status> statuses;
String user;
user = "Replace this with the screen name whose feeds you want to fetch";
statuses = twitter.getUserTimeline(user);
Log.i("Status Count", statuses.size() + " Feeds");
} catch (TwitterException te) {
te.printStackTrace();
}
I used twitter 4j 3.03.jar for this.
How can I get a Twitter public timeline with no Access Token and Secret using Twitter4j?
Oh, that is very simple. YOU CAN'T.
Twitter a a data based company. 99% of the property of the company (I mean what the company owns) is data. It would be contra-productive, to give this data for free out to other people/businesses.
If the thing you want, would be possible, then there would be an easy way to backup the whole twitter database.
That is why they let you register an account for each application, that wants to use the API and limit each account to a certain amount of API calls per time frame. Of course they also want to prevent their network from spam etc.
If you want get tweets without user authenticating, you can use Application-only Authentication, because the user doesn´t need to login.
With Application-only authentication Twitter offers applications the ability to issue authenticated requests on behalf of the application itself (as opposed to on behalf of a specific user)
The application-only auth flow follows these steps:
An application encodes its consumer key and secret into a specially encoded set of credentials.
An application makes a request to the POST oauth2/token endpoint to exchange these credentials for a bearer token.
When accessing the REST API, the application uses the bearer token to authenticate.
NOTE: Because twitter4j has added this feature recently, you should use the last snapshot library.
An example using it:
private ConfigurationBuilder builder;
private Twitter twitter;
private TwitterFactory factory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.init_act_layout);
// setup
builder = new ConfigurationBuilder();
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
Configuration configuration = builder.build();
factory = new TwitterFactory(configuration);
((MyApp) (MyApp.getApp())).setTFactory(factory);
if (isNeededTwitterAuth()) {
twitter = factory.getInstance();
//Get the token async and save it
}
//Search tweets
}
/*
* Checks if twitter access token is already saved in preferences
*
* #return true if auth needed
*/
private boolean isNeededTwitterAuth() {
SharedPreferences settings = getSharedPreferences(Constants.TWITTER_PREFERENCES, Context.MODE_PRIVATE);
String twitterAccesToken = settings.getString("bearerAccessToken", "");
String twitterTokenType = settings.getString("bearerTokenType", "");
return ((twitterAccesToken.length() == 0) && (twitterTokenType.length() == 0));
}
}
To get the bearer token, do it out of Main UI thread to avoid Network exception, f.i. using AsyncTask:
#Override
protected OAuth2Token doInBackground(Void... params) {
OAuth2Token bearerToken = null;
try {
bearerToken = twitter.getOAuth2Token();
} catch (TwitterException e) {
e.printStackTrace();
}
return bearerToken;
}
When you obtain the bearer token, save it:
SharedPreferences appSettings = getSharedPreferences(Constants.TWITTER_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = appSettings.edit();
prefEditor.putString("bearerAccessToken", result.getAccessToken());
prefEditor.putString("bearerTokenType", result.getTokenType());
prefEditor.commit();
And to use the bearer token:
OAuth2Token bearerToken = new OAuth2Token(bearerTokenType, bearerAccesstoken);
twitter.setOAuth2Token(bearerToken);
And search tweets (always out of Main thread):
#Override
protected QueryResult doInBackground(Void... params) {
twitter.setOAuth2Token(bearerToken);
Query query = new Query();
[...]
result = twitter.search(query);
A complete explanation in the blog (in Spanish...)
And a complete example in the twitter4j github
Hope it helps!

Send App request to all friends in Facebook using 'Requests Dialog' in Android

I want to know how to send app request to all my facebook friends from android app. I tried in graph API. But, couldn't get it done.
https://graph.facebook.com/apprequests?ids=friend1,friend2&message='Hi'&method=post&access_token=ACCESS_TOKEN
I know this is a Duplicate question. But, couldn't find an answer yet.
I'm getting this error on the above API.
"All users in param ids must have accepted TOS."
I hope there will be a way to send app request to all friends from mobile on a click. Please share it.
The error message you receive ("All users in param ids must have accepted TOS") is because you are trying to send an app generated request to a user who is not connected to your app.
See the developer docs here.
Requests sent with the request dialog and app generated requests are different and you can't use app generated requests to invite users to your app.
Sending Facebook app requests are not available via the graph api. You can use the app requests java-script dialog to send the request though, you would just need to specify the user's id in the "to" property as detailed in the documentation.
Sample function:
<script>
FB.init({ appId: '**appId**', status: true, cookie: true, xfbml : true });
function sendRequest(to) {
FB.ui({method: 'apprequests', to: to, message: 'You should learn more about this awesome site.', data: 'tracking information for the user'});
return false;
}
</script>
Then just wire an onclick for each image to something like onclick="return sendRequest('**friendId**');"
Also you can call this function in javascript: It will give you all friends with photos. Also group of friends who are currently using same app. You can send request to any of them.
function sendRequestViaMultiFriendSelector() {
FB.ui({
method: 'apprequests',
message: "You should learn more about this awesome site."
});
}
See Facebook Friend Request - Error - 'All users in param ids must have accepted TOS'
Have you seen demo of "Hackbook" in the developer.facebook.com ?
You can refer HACKBOOK APP REQUEST FROM HERE.
You can achieve to post the app request to only one friend by below code.
Code:
Bundle params = new Bundle();
JSONObject attachment = new JSONObject();
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
JSONObject prop2 = new JSONObject();
JSONObject media = new JSONObject();
JSONStringer actions = null;
try {
attachment.put("name", "YOUR_APP");
attachment.put("href", "http://www.google.com/");
attachment.put("description", "ANY_TEXT");
media.put("type", "image");
media.put("src", "IMAGE_LINK");
media.put("href", "http://www.google.com/");
attachment.put("media", new JSONArray().put(media));
prop1.put("text", "www.google.com");
prop1.put("href", "http://www.google.com");
properties.put("Visit our website to download the app", prop1);
/* prop2.put("href", "http://www.google.com");
properties.put("iTunes Link ", prop2);*/
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
actions = new JSONStringer().object()
.key("name").value("APP_NAME")
.key("link").value("http://www.google.com/").endObject();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("ACTIONS STRING: "+actions.toString());
System.out.println("ATTACHMENT STRING: "+attachment.toString());
params.putString("actions", actions.toString());
params.putString("attachment", attachment.toString()); // Original
params.putString("to", "YOUR_FRIEND_FACEBOOK_ID");
Utility.mFacebook.dialog(getParent(), "stream.publish", params,new PostDialogListener());
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(), ""+getResources().getString(R.string.facebook_response_msg_posted), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), ""+getResources().getString(R.string.facebook_response_msg_not_posted), Toast.LENGTH_SHORT).show();
}
}
}
Above code works perfect if you want to post the Apprequest only on One friend's wall. If you want to post on all then you have to make asynckTask which runs for all the friends post and post App request on all walls.
Update
Here is the link in PHP that have done same work to send request to all Facebook friends.
And [here it is clearly explained3 that it is blocked by Facebook to send a Friend Request to more then 15-20 friends.
Now, you have to only one option to do it is, use above code in AsyncTask to send Friend Request to all Friends One-by-One.

fbShare in android

Can anybody suggest a good method for creating a facebook share implementation for my application.
I have created the test account and API key for the facebook developer site...
I need to implement in such a way that,when the fbshare button is clicked,a particular content(dynamic content) should be posted as a status link in the corresponding linked facebook account...
Apart from the fb developers,i need some other way of implementing it...
Suggestions expected...(possibly better results expected)
Hi use this method in your code in facebook handler class
public void postToFBWall(final String message, final String image){
Thread thread = new Thread(){
public void run(){
try{
String descripton = "This is the plain text copy next to the image. All work and no play makes Jack a dull boy.";
Bundle parameters = new Bundle();
parameters.putString("message", message);// message to be posted on facebook wall
parameters.putString("link", image);//link of image to be posted on facebook wall
parameters.putString("name", "My wish");// name of link
parameters.putString("description", descripton);// description of you post
String response1 = facebook.request("me/feed", parameters, "POST");
Log.v("facebook response", response1);
}catch (Exception e) {
}
}
};thread.start();
}
Try this one
https://developers.facebook.com/docs/mobile/android/hackbook/
it may helps you.

Categories

Resources