How to get user information from twitter in android app? - android

I am integrating twitter in my android app. I am able to authorize the app for the user. Now, I am looking for the API which gives me logged users information like first name, last name, email, etc.
I had done this for facebook with
facebook.request("me");
Now how to get user info from twitter?
I am using twitter4j-core-android2.2.3.jar. Plz let me know is there a way to get user info.

Finally I got user information.
use the access token you get after
accessToken = twitterConnection.getOAuthAccessToken
(requestToken,editPinCode.getText().toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken.getTokenSecret());
long userID = accessToken.getUserId();
User user = twitterConnection.showUser(userID);
user.getName();
Thanks.

There are a few tutorials here that can help you get an app running with twitter..
if you just need to retrieve info for a specific user, you can look here (includes source code):
Basic Adroid Twitter Integration
If you want to interact with twitter (e.g. post updates etc) then you will need to setup OAuth connection:
Android and Twitter integratin using OAuth

Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false).enqueue(new Callback<User>()
{
#Override
public void success(Result<User> userResult)
{
try
{
User user = userResult.data;
// twitterImage = user.profileImageUrl;
} catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void failure(TwitterException e)
{
}
});

You cannot get Email from the twitter OAuth unless or untill your app is whitelisted.
For more Info
Email ID from Twitter

You can check bellow code: To get user info you can use Twitter Fabric SDK. Its documentation is here and here
twitterButton.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) {
Log.d("ls",e.getMessage());
}
});
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.app_name),
Toast.LENGTH_SHORT).show();
}
});
Here twitterButton is
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
In this response you can get All credential without user Email.

Related

Not getting Twitter login screen if Twitter is not installed on Android phone

I'm using the Twitter kit for having a Login Facility on an Android App.
I'm using these depenencies -
compile 'com.twitter.sdk.android:twitter-core:3.1.1'
compile 'com.twitter.sdk.android:tweet-ui:3.1.1'
I'm initializing it like this in the Application Context class -
TwitterConfig config = new TwitterConfig.Builder(getApplicationContext())
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(getString(R.string.Twitter_CONSUMER_KEY), getString(R.string.Twitter_CONSUMER_SECRET)))
.debug(false)
.build();
Twitter.initialize(config);
In my Activity I have this code for Click listener on a button that calls Twitter API for Login. twitter_login is a TextView. -
twitter_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTwitterAuthClient = new TwitterAuthClient();
mTwitterAuthClient.authorize(getActivity(), new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
twitter_token = authToken.token;
twitter_secret = authToken.secret;
if (mTwitterAuthClient != null) {
(mTwitterAuthClient.requestEmail(session, new com.twitter.sdk.android.core.Callback<String>() {
#Override
public void success(Result<String> emailResult) {
emailFromTwitter = emailResult.data;
}
#Override
public void failure(TwitterException e) {
String error_message = e.getMessage();
}
});
}
}
#Override
public void failure(TwitterException e) {
}
});
I have this inside onActivityResult -
mTwitterAuthClient.onActivityResult(requestCode, resultCode, data);
The case is that
When I click on twitter_login, if I have the Twitter App installed on my Android phone, it shows the Authorization screen and login works fine.
But I don't even get a Login Screen if Twitter App is not installed on my Android phone when I click on twitter_login. In this case how to prompt the user to enter his/her twitter credentials for login ?
Why is it so ? How to fix it ? Am I doing anything wrong ?
You have to add the call back URL Open your application in https://apps.twitter.com and select your app, in settings tab add callback URL
as below
twittersdk://
Ref : link

aws cognito with facebook login? - android

so im really confused on how the facebook login works with aws cognito in android. I was able to hook aws cognito up and the facebook log in just fine. The aws cognito guide gives me these lines of code:
Map<String, String> logins = new HashMap<String, String>();
logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken());
credentialsProvider.setLogins(logins);
couple questions:
1.Where do i put these lines of code?
2.How do i set up cognito user equal to the login facebook user?
3.And basically, whats a working example of this?
Hope you guys can help!
This is the following code where I have used the facebook login with federated identities from the congnito. first you need to set up the CognitoSyncManagerFile with the appropriate login credentials with the pool details . And then the following code as follows .
//initialize the facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//If access token is already here, set fb session
final AccessToken fbAccessToken = AccessToken.getCurrentAccessToken();
if (fbAccessToken != null) {
setFacebookSession(fbAccessToken);
// btnLoginFacebook.setVisibility(View.GONE);
}
btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook);
btnLoginFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// start Facebook Login
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
btnLoginFacebook.setVisibility(View.GONE);
new GetFbName(loginResult).execute();
setFacebookSession(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Facebook login cancelled",
Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(MainActivity.this, "Error in Facebook login " +
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
});
//Set the session with the following method
private void setFacebookSession(AccessToken accessToken) {
Log.i(TAG, "facebook token: " + accessToken.getToken());
CognitoSyncClientManager.addLogins("graph.facebook.com",
accessToken.getToken());
}
For more information follow the below url
https://github.com/awslabs/aws-sdk-android-samples/tree/master/CognitoSyncDemo
Put this in a spot where your credentials provider has already been initialized, where you have just logged in to Facebook for the user in question.
Once you have included this in the logins map, call credentialsProvider.refresh(). This will link the login to the user's identity.
The official AWS samples repo has an android sample that does all this.

Firebase authWithOauthToken is not working

I am developing an app in Android using firebase.I have created the login activity where i have a method that logs user in when they pass the credentials(user creation is already done).Then i will save the token recieved in onAuthenticated callback so that i can log user in automatically next time when he/she opens the app without asking to enter the credentials.
Here is the code
private void loginWithPassword(final String email, String password) {
progressDialog.show();
FirebaseConnections.getConnection().authWithPassword(email, password,
new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// Authentication just completed successfully :)
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError error) {
// Something went wrong :(
dismissProgressDialog();
Snackbar.make(parentView, error.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
And then i check onCreate whether we have token token to log user in
private void checkIfTokenExistAndLogin() {
if (IGStorePreference.getInstance().isPrefExists(Constants.TOKEN)) {
progressDialog.show();
String provider = IGStorePreference.getInstance().getString(Constants.PROVIDER);
String token = IGStorePreference.getInstance().getString(Constants.TOKEN);
FirebaseConnections.getConnection().authWithOAuthToken(provider, token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
dismissProgressDialog();
Snackbar.make(parentView, firebaseError.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
}
But the problem is that i am getting an error while login user with authWithOAuthToken.Please help what i am missing.
This is the error i recieve everytime.
FirebaseError: Invalid authentication credentials provided.
authWithOAuthToken is used to login with a social provider. For example, user signs in with Google and gets an OAuth token returned from Google. Then app sends this OAuth token to Firebase auth server via authWithOAuthToken. User can log in after server verifies the OAuth token.
In your case, user logged in with email/password. The token you received was a Firebase auth token issued by Firebase auth server not an OAuth token issued by social provider.
Please refer to the doc for details: https://firebase.google.com/support/guides/firebase-android#sign_a_user_in_with_a_social_provider_numbered

Disabling graph api calls without app secret

I am developing an android app for sharing images. I wish to integrate Facebook SDK in the app.
I am getting user access token from the app. Then this token will be used from the server to download and store images in our server. I want to make our user's information safe. I don't want someone else to get user information if they somehow get access to the token from my app.
I have enabled Require App Secret in Facebook app dashboard, but when i call the graph api with this access token from my computer, it is giving me a valid response (i.e. I am able to extract user information with the token outside the app without using app_secret). However, when I get access to the token of Test users from the developer dashboard and try making calls to the graph API, I am getting:
"error": {
"message": "The access token could not be decrypted",
"type": "OAuthException",
"code": 190
}
Which is exactly what I wanted. So I am doing something wrong when I collect the user's token. Below is my logging in code:
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_photos, user_friends"));
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
private ProfileTracker mProfileTracker;
#Override
public void onSuccess(final LoginResult loginResult) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile1, Profile profile) {
/**
* Getting userId and storing to SP as long
*/
final String userId = loginResult.getAccessToken().getUserId();
/**
* Getting facebook profilePic, Name and token and storing to SP
*/
String profileImgUrl = "https://graph.facebook.com/" + userId + "/picture?type=large";
final String token = loginResult.getAccessToken().getToken();
if (profile == null) return;
String name = profile.getName();
}
};
mProfileTracker.startTracking();
}
#Override
public void onCancel() {
Log.d("facebook - onCancel", "cancelled");
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Log.d("facebook - onError", e.getMessage());
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
});
Can anyone help me in finding the problem? Thanks in advance.

How to integrate Twitter in my App for Login and Tweet - Android

I am building an application in which I want to integrate Twitter. I have gone through several docs and links but still I am at the starting point.
I need two functionality for this app:
Login through Twitter account
Tweet through logged in account
I know that we can use Twitter 4J library for this but I don't know how to use this.
Also I would like to know whether I can get any response Id if a user tweets successfully.
I have already created my Twitter Test app and I have the Consumer Key, Consumer Secret Key. Please help me to sort out this.
Use ASNE for your requirement. Read out this tutorial for more details about ASNE.
Twitter also released Fabric which is a set of tools like Crashylitics, Admob but also kits which include a SDK for integratting twitter in your app.
Fabric Twitter kit : https://dev.twitter.com/twitter-kit/android/twitter
Installation instruction : https://dev.twitter.com/fabric/android/integrating
i really recommend to take a look at this example from Twitter that demonstrate how to use Fabric kits on your android app, it shows you how to login with twitter account or digits, compose tweets, Search, Crashlytics...
for example, for login :
private void setUpTwitterButton() {
twitterButton = (TwitterLoginButton) findViewById(R.id.twitter_button);
twitterButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
SessionRecorder.recordSessionActive("Login: twitter account active", result.data);
startThemeChooser();
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.toast_twitter_signin_fail),
Toast.LENGTH_SHORT).show();
Crashlytics.logException(exception);
}
});
}
hope this helps
I assume you want the post the status to twitter from android application.
To answer your queries:
Login through Tweet- We will use OAuth protocol to integrate the twitter to android application
Tweet through logged in account- For this we will be using Twitter4J library and post the tweets from android application
Having said that,
We cannot post directly to twitter, so we have to use Async Task for it.
You can use following code for reference:
new UseTweeter().execute(); // async task call
public class UseTweeter extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
pdProgressCircleSend=new ProgressDialog(getActivity());
pdProgressCircleSend.setMessage(Constants.POSTING_TWEET);
pdProgressCircleSend.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
TweetThisMessage(); //Call for posting status
return null;
}
#Override
protected void onPostExecute(String s) {
if(pdProgressCircleSend!=null && pdProgressCircleSend.isShowing()) {
pdProgressCircleSend.dismiss();
}
Toast.makeText(getContext(), "Tweeted Successfully", Toast.LENGTH_SHORT).show();
}
}
public void TweetThisMessage(){
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthAccessToken(accesstoken);
builder.setOAuthAccessTokenSecret(accesstokensecret);
builder.setOAuthConsumerKey(consumerkey);
builder.setOAuthConsumerSecret(consumersecret);
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
Twitter twitter = new TwitterFactory().getInstance(auth);
StatusUpdate status=new StatusUpdate(sTweet);
status.setMedia(f);
try{
Log.i("TAGTweet","sTweet in TweetThisMessage is sTweet"+ sTweet);
twitter.updateStatus(sTweet);
}catch (TwitterException e){
e.printStackTrace();
return;
}

Categories

Resources