Does anyone know if there is a way to pull a signed in users profile picture to be placed through the app, to maybe place it on the ActionBar as they navigate around?
hints, tips, examples, downloads all welcome :)
If you can help me, please assume I very little knowledge regarding anything outside basic Java!
Again, thanks people x
You can get a user's profile image by using /1.1/users/show.json. You can refer to REST API URLs for Twitter data.
By extending TwitterApiClient we can retrieve Twitter data from the URL.
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface UsersService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") Long userId,
#Query("screen_name") String screenName,
#Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
Next, get the UsersService and call its show method, passing in the defined query parameters. I defined the query parameters based on the ones that are documented.
new MyTwitterApiClient(session).getUsersService().show(12L, null, true,
new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("twittercommunity", "user's profile url is "
+ result.data.profileImageUrlHttps);
}
#Override
public void failure(TwitterException exception) {
Log.d("twittercommunity", "exception is " + exception);
}
});
Courtesy: https://twittercommunity.com/t/android-get-user-profile-image/30579/2
This is how I got mine to work:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false,false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String profilebannerurl = userResult.data.profileBannerUrl;
String profileurl = userResult.data.profileImageUrl;
}
#Override
public void failure(TwitterException e) {
}
});
I have place this piece of code within my LoginButton callback method:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) { <insert here> }
I did it with a custom button and this is the code that is executed by it's onClick listener :
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_API_KEY, TWITTER_API_SECRET);
Fabric.with(activity, new Twitter(authConfig));
TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false, new com.twitter.sdk.android.core.Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d(TAG, "Twitter log in success");
String userName = result.data.screenName;
int userId = result.data.id;
String pictureUrl = result.data.profileImageUrl;
String coverUrl = result.data.profileBannerUrl;
}
#Override
public void failure(TwitterException e) {
Log.d(TAG, "Twitter log in error : " + e.getMessage());
}
});
I should ask the user to authorize access to your app and log him in if he accepts.
Related
I am doing an android app with TwitterLogin Integration using Twitter Api. Here I am not using any twitter 4j and fabric . I am able to get Twitter user name but unable to get Email Id. searched more for this issue, but got nothing with twitter api.
I followed this twitterAPI to login
and this is my code
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
System.out.println("=======twitterlogin success=======");
String username=result.data.getUserName();
getUsertwitteremail();
}
#Override
public void failure(TwitterException exception) {
System.out.println("=======twitterlogin failure==========");
}
});
please someone help me to get the details including email.
First of all make sure Request email addresses from users is checked for your Twitter app
Check out the code below and get the email
mTwitterAuthClient.authorize(this, new com.twitter.sdk.android.core.Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
long userId = session.getUserId();
String userNa = session.getUserName();
Log.d("twitter check", userNa + " " + secret);
mTwitterAuthClient.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result) {
Log.d("email", result.data);
// Do something with the result, which provides the email address
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
please enable permissions for email access form your twitter app console.
from here
https://apps.twitter.com/app/14057942/permissions
I use the following code:
UserTimeline userTimeline = new UserTimeline.Builder().screenName("ZainAlabdin878").build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter(MainActivity.this, userTimeline);
System.out.println(adapter.getCount()+"");
I get the output 0 although I have tweets.
Am I doing something wrong?
what I am trying to achieve is to get a list of tweets of a certain user. I'm using android studio and plugin.
*my goal is not to display the list but rather to get a List
many thanks.
final TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(context, new Twitter(authConfig), new TweetUi());
TwitterCore.getInstance().logInGuest(new Callback<AppSession>() {
#Override
public void success(Result<AppSession> result) {
AppSession session = result.data;
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
twitterApiClient.getStatusesService().userTimeline(tweetId, screenName, tweetCount, null, null, false, false, false, true, new Callback<List<Tweet>>() {
#Override
public void success(Result<List<Tweet>> listResult) {
for (Tweet tweet : listResult.data) {
// here you will get list
}
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
}
#Override
public void failure(TwitterException e) {
Log.e(TAG, "Load Tweet failure", e);
}
});
more details available here
Here's the code you'll need to actually fetch the Tweet objects:
ArrayList<Tweet> tweets = new ArrayList<>();
TwitterCore.getInstance().getApiClient(session).getStatusesService()
.userTimeline(null,
"screenname",
10 //the number of tweets we want to fetch,
null,
null,
null,
null,
null,
null,
new Callback<List<Tweet>>() {
#Override
public void success(Result<List<Tweet>> result) {
for (Tweet t : result.data) {
tweets.add(t);
android.util.Log.d("twittercommunity", "tweet is " + t.text);
}
}
#Override
public void failure(TwitterException exception) {
android.util.Log.d("twittercommunity", "exception " + exception);
}
});
You'll need to run this in a new Thread (not the UI Thread)
EDIT
*Technically you don't have to run this in a new thread because it's asynchronous (someone please correct me here if I'm wrong). I know other Twitter API calls are async, so I'm assuming this one is too, although I cannot find where the actual call is happening in the Fabric source..*
Here's the full list of parameters for userTimeline() from the Fabric SDK
void userTimeline(#Query("user_id") Long var1, #Query("screen_name") String var2, #Query("count") Integer var3, #Query("since_id") Long var4, #Query("max_id") Long var5, #Query("trim_user") Boolean var6, #Query("exclude_replies") Boolean var7, #Query("contributor_details") Boolean var8, #Query("include_rts") Boolean var9, Callback<List<Tweet>> var10);
I'm logging in with twitter using Fabric.
This is how I fetch the user data:
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
AccountService ac = Twitter.getApiClient(result.data).getAccountService();
ac.verifyCredentials(true, true, new Callback<com.twitter.sdk.android.core.models.User>() {
#Override
public void success(Result<com.twitter.sdk.android.core.models.User> result) {
String imageUrl = result.data.profileImageUrl;
String email = result.data.email;
String userName = result.data.name;
System.out.println(imageUrl);
System.out.println(email);
System.out.println(userName);
}
#Override
public void failure(TwitterException e) {
}
});
}
This is working fine, except that the email variable is null when I print to log. Is there an other way of fetching the user email?
-Here is the Solution!
twitauthobj.requestEmail(twitsessionobj,new Callback<String>() {
#Override
public void success(Result<String> stringResult) {
'You code here'
}
#Override
public void failure(TwitterException e) {
}
});
-Thanks let me inform if t doesnt work!
To bypass Twitter's useless request email activity and to fix a leak, I dug through the source code and pulled this out:
new Retrofit.Builder()
.client(getClient(sessionResult))
.baseUrl(new TwitterApi().getBaseHostUrl())
.addConverterFactory(getFactory())
.build()
.create(EmailService.class)
.getEmail()
.enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
String email = result.data.email;
// Handle the result
if (email == null) {
TwitterProvider.this.failure(
new TwitterException("Your application may not have access to"
+ " email addresses or the user may not have an email address. To request"
+ " access, please visit https://support.twitter.com/forms/platform."));
} else if (email.equals("")) {
TwitterProvider.this.failure(
new TwitterException("This user does not have an email address."));
} else {
mCallbackObject.onSuccess(createIdpResponse(sessionResult.data, email));
}
}
#Override
public void failure(TwitterException exception) {
TwitterProvider.this.failure(exception);
}
});
private OkHttpClient getClient(Result<TwitterSession> sessionResult) {
return OkHttpClientHelper.getOkHttpClient(
sessionResult.data,
TwitterCore.getInstance().getAuthConfig(),
TwitterCore.getInstance().getSSLSocketFactory());
}
private GsonConverterFactory getFactory() {
return GsonConverterFactory.create(
new GsonBuilder()
.registerTypeAdapterFactory(new SafeListAdapter())
.registerTypeAdapterFactory(new SafeMapAdapter())
.registerTypeAdapter(BindingValues.class, new BindingValuesAdapter())
.create());
}
EmailService:
interface EmailService {
#GET("/1.1/account/verify_credentials.json?include_email=true?include_entities=true?skip_status=true")
Call<User> getEmail();
}
I've been trying to implement Fabric to get a list of the 5 latest tweet from a user. It worked great for a few hours and then it stopped working. I would like to do this without having the user log in, and as far as I can tell the API allows guest-logins to read tweets, but maybe this has a greater effect on the Rate Limit?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics());
TwitterCore.getInstance().logInGuest(new Callback() {
#Override
public void success(Result result) {
AppSession session = (AppSession) result.data;
getTweets();
}
#Override
public void failure(TwitterException exception) {
// unable to get an AppSession with guest auth
}
});
}
public void getTweets() {
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.userTimeline([USERID], null, 5, null, null, null, true, null, false, new Callback<List<Tweet>>() {
#Override
public void success(Result <List<Tweet>> result) {
for(Tweet Tweet : result.data) {
tweetList.add(Tweet.text);
}
createListView();
}
public void failure(TwitterException exception) {
Log.e("Failure", exception.toString());
exception.printStackTrace();
}
});
}
When I don't get the 403 everything works perfectly and my list gets populated.
Now, it's entirely possible that there is just something wrong my code that gets me rate limit blacklisted? Otherwise; do I need have the user log in just to show them 5 tweets? Or should I implement some sort of serverside-cache?
Thankful for any tips/help.
I think I might have it figured out. Looks like you have to save the session from the success method in the logInGuest callback and then pass that to getApiClient. Here's some code that's working for me so far:
private TweetViewFetchAdapter adapter;
...
adapter = new TweetViewFetchAdapter<CompactTweetView>(getActivity());
...
TwitterCore.getInstance().logInGuest( new Callback<AppSession>() {
#Override
public void success(Result<AppSession> appSessionResult) {
AppSession session = appSessionResult.data;
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
twitterApiClient.getStatusesService().userTimeline(null, "RadioOkinawa864", 10, null, null, false, false, false, true, new Callback<List<Tweet>>() {
#Override
public void success(Result<List<Tweet>> listResult) {
adapter.setTweets(listResult.data);
}
#Override
public void failure(TwitterException e) {
Toast.makeText(getActivity().getApplicationContext(), "Could not retrieve tweets", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
#Override
public void failure(TwitterException e) {
Toast.makeText(getActivity().getApplicationContext(), "Could not get guest Twitter session", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
When using logInGuest, be aware that guest AppSessions will expire after some time. Your application must handle expiration TwitterExceptions and request another guest AppSession. For example,
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(guestAppSession);
twitterApiClient.getSearchService().tweets("#fabric", null, null, null, null, 50, null, null, null, true, new Callback<Search>() {
#Override
public void success(Result<Search> result) {
// use result tweets
}
#Override
public void failure(TwitterException exception) {
final TwitterApiException apiException = (TwitterApiException) exception;
final int errorCode = apiException.getErrorCode();
if (errorCode == TwitterApiConstants.Errors.APP_AUTH_ERROR_CODE || errorCode == TwitterApiConstants.Errors.GUEST_AUTH_ERROR_CODE) {
// request new guest AppSession (i.e. logInGuest)
// optionally retry
}
}
});
Note that AppSessions may only be used to make API requests that do not require a user context. For example, you cannot Tweet with an AppSession. You can get a user's timeline of public Tweets. See TwitterKit Android REST API docs.
Finally, if you are using the TweetUtils.loadTweet or TweetUtils.loadTweets helpers from the TweetUi kit of the Twitter kit group, setting up guest auth and handling expiration is performed automatically, you need not call logInGuest yourself.
In my case the api returned 403 forbidden with the following message Your app may not allow guest auth. Please talk to us regarding upgrading your consumer key.
Be sure your are not in the same status.
I'm trying to implement a simple application that uses Twitter kit. The problem is that i'm not able to get the profile picture.Any help would be appreciated.
Thanks
From the official doc:
You can obtain a user’s most recent profile image from GET users/show. Within the user object, you’ll find the profile_image_url
and profile_image_url_https fields. These fields will contain the
resized “normal” variant of the user’s uploaded image. This “normal”
variant is typically 48x48px.
By modifying the URL, you can retrieve other variant sizings such as
“bigger”, “mini”, and “original”.
Following the code:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false, false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String email = userResult.data.email;
// _normal (48x48px) | _bigger (73x73px) | _mini (24x24px)
String photoUrlNormalSize = userResult.data.profileImageUrl;
String photoUrlBiggerSize = userResult.data.profileImageUrl.replace("_normal", "_bigger");
String photoUrlMiniSize = userResult.data.profileImageUrl.replace("_normal", "_mini");
String photoUrlOriginalSize = userResult.data.profileImageUrl.replace("_normal", "");
}
#Override
public void failure(TwitterException exc) {
Log.d("TwitterKit", "Verify Credentials Failure", exc);
}
});
For further information refer to Twitter API Documentation | Profile Images and Banners
As of Nov 2016. This works.
There is a change in the implementation of verify credentials.
Call<User> user = TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false);
user.enqueue(new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String email = userResult.data.email;
// _normal (48x48px) | _bigger (73x73px) | _mini (24x24px)
String photoUrlNormalSize = userResult.data.profileImageUrl;
String photoUrlBiggerSize = userResult.data.profileImageUrl.replace("_normal", "_bigger");
String photoUrlMiniSize = userResult.data.profileImageUrl.replace("_normal", "_mini");
String photoUrlOriginalSize = userResult.data.profileImageUrl.replace("_normal", "");
}
#Override
public void failure(TwitterException exc) {
Log.d("TwitterKit", "Verify Credentials Failure", exc);
}
});
Found the answer.
There is a callback which returns you the User object.
TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(true, true, false).enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
}
#Override
public void failure(TwitterException exception) {
}
});
On the success branch, you can get the User object by calling:
User user = userResult.data;
And from this object you can get all the information form the user. For the profile image:
String profileImage = user.profileImageUrl;
from gradle 2.0.0 and up use following method:
Call<User> userResult=Twitter.getApiClient(session).getAccountService().verifyCredentials(true,false);
userResult.enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
User user = userResult.data;
String profileImage= user.profileImageUrl;
}
#Override
public void failure(TwitterException exception) {
}
});