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();
}
Related
Integrate twitter in my app, when user logged in through twitter I show the follower list for sending messages but when called /1.1/followers/list.json API I got the null response , Do I need any permission to access API ?
{protocol=h2, code=400, message=, url=https://api.twitter.com/1.1/followers/list.json?screen_name=(screenname)&cursor=-1&skip_status=true}
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
e("********", "----result--->>>>" + result.response);
/* TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret; */
/***********************After login****************/
APIService inf1 = MyApplication.getRetro(Login.this, "https://api.twitter.com").create(APIService.class);
final Call<JsonElement> res1 = inf1.show("-1","(screenName)",true,false);
// "/1.1/followers/list.json?include_user_entities=false&screen_name=twitterdev&skip_status=true&cursor=-1
res1.enqueue(new retrofit2.Callback<JsonElement>() {
#Override
public void onResponse(#NonNull Call<JsonElement> call, #NonNull Response<JsonElement> response) {
try {
JSONObject mReturn = new JSONObject(response.body().toString());
e("-------->>", "*******onResponse*******"+mReturn);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NonNull Call<JsonElement> call, #NonNull Throwable t) {
}
});
/************************************************/
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
API:
#GET("/1.1/followers/list.json")
Call<JsonElement> show( #Query("cursor")String cursor,
#Query("screen_name")String var,
#Query("skip_status")boolean skip_status,
#Query("include_user_entities")boolean include_user_entities);
I am trying to retrieve the text from every tweet of a user.
I don't send a get request.
I successfully connect with a tweeter account to my app with :
activity.client.authorize(activity, new Callback<TwitterSession>()
{
#Override
public void success(Result<TwitterSession> result)
{
Toast.makeText(getApplicationContext(), "Login worked", Toast.LENGTH_LONG).show();
writeInfile(result);
}
#Override
public void failure(TwitterException e)
{
Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
}
});
With the result I can access informations from my user such as his id or his name.
I also have the UserTimeLine
final UserTimeline userTimeline = new UserTimeline.Builder()
.userId(result.data.getUserId())
.build();
How can I get his tweets or the id of his tweets from there ?
Thank you
I managed to do it by looking at every methods given by auto completion so if it can help anyone, here is how I did it :
void writeData(ContentResolver contentResolver)
{
activity.client.authorize(activity, new Callback<TwitterSession>()
{
#Override
public void success(Result<TwitterSession> result)
{
writeInfile(result);
}
#Override
public void failure(TwitterException e)
{
Log.e("Twitter Log in", e.toString());
}
});
}
void writeInFile(Result<TwitterSession> result)
{
userTimeline = new UserTimeline.Builder()
.userId(result.data.getUserId())
.includeRetweets(false)
.maxItemsPerRequest(200)
.build();
userTimeline.next(null, callback);
}
Callback<TimelineResult<Tweet>> callback = new Callback<TimelineResult<Tweet>>()
{
#Override
public void success(Result<TimelineResult<Tweet>> searchResult)
{
List<Tweet> tweets = searchResult.data.items;
for (Tweet tweet : tweets)
{
String str = tweet.text; //Here is the body
maxId = tweet.id;
}
if (searchResult.data.items.size() == 200)
userTimeline.previous(maxId, callback);
else
closeOutputFile();
}
#Override
public void failure(TwitterException error)
{
//Do something
}
};
I have a Twitter Login created following this steps http://docs.fabric.io/android/twitter/authentication.html and It displays the Username Except the User's Full name.
This is my code below
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
long userID = result.data.getUserId();
//This throws an Error Cannot find symbol showUser()
User user = twitter.showUser(userID);
//This throws error as well
String fullname= user.getName();
Log.d("login:", "twitter:success");
Log.d("username", result.data.getUserName());
Log.d("full name", fullname);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
Please how exactly can I get User's fullname?
Use TwitterApiClient and User like this:
Twitter
.getApiClient(session)
.getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void failure(TwitterException e) {
}
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
.... access User fields ....
}
});
You can use this function for getting user name:
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
verifier);
mAccessToken = new AccessToken(
mHttpOauthConsumer.getToken(),
mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
Log.i("user.getName()="+user.getName(), "786");
try{
firstName=user.getName().split(" ")[0];
lastName=user.getName().split(" ")[1];
}catch(Exception e){
e.printStackTrace();
firstName = user.getName();
lastName = "";
}
Log.i("firstName="+firstName+" lastName="+lastName, "786");
UserId=user.getId();
what = 0;
} catch (Exception e) {
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
after login success, in your public void success(Result<TwitterSession> result) method, use this code.
#Override
public void success(Result<TwitterSession> result) {
TwitterSession sess = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterApiClient apiClient = new TwitterApiClient(sess);
final Call<com.twitter.sdk.android.core.models.User> getUserCall = apiClient
.getAccountService()
.verifyCredentials(true, false,true);
new Thread(new Runnable() {
#Override
public void run() {
try {
com.twitter.sdk.android.core.models.User user = getUserCall.execute().body();
String realname = user.name;
long realid = user.id;
//similarly you can get user's other properties like location etc
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
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.
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) {
}
});