Android how to get user's full name after authentication with Twitter - android

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();
}

Related

why email id is not accessible via graph api even after enabling the option of sharing it in profile

My code is as shown below:
facebookButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(LogInActivity.this,
Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//set login status
SessionManager.get(LogInActivity.this).setLoginStatus(true);
graphRequest(loginResult);
}
#Override
public void onCancel() {
// not called
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
// not called
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
});
private void graphRequest(LoginResult loginResult) {
showProgressDialog();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (object.has("email")) {
//store session manager
email = object.getString("email");
SessionManager.get(LogInActivity.this).setEmailId(email);
}
if (object.has("id")) {
faceBookId = object.getString("id");
picUrl = "https://graph.facebook.com/" + faceBookId
+ "/picture?type=large";
//store session manager
SessionManager.get(LogInActivity.this).setProfilePic(picUrl);
// downLoadImage(url);
}
if (object.has("name")) {
//store session manager
name = object.getString("name");
SessionManager.get(LogInActivity.this).setPersonName(name);
}
downLoadImage(picUrl, name, email, "0");
// Toast.makeText(getApplicationContext(), email, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
}
The problem here is , I am not able to get email id even after enabling Allow friends to include my email address in Download Your Information option in my facebook profile, is there any other way to get email id?
try it
String email = "";
try {
email = URLDecoder.decode(object.optString("email")
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Unable to fetch facebook profile picture, to insert in ImageView

I am unable to fetch the facebook profile picture, in order to display it in my fragment. Name, Birthday and link is fetched successfully, however the application stops working when I try to fetch the profile picture. How to get rid of this situation?
private FacebookCallback<LoginResult> callback=new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken=loginResult.getAccessToken();
Profile profile=Profile.getCurrentProfile();
//DisplayMessage(profile);
GraphRequest request=GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try{
tv1=(TextView)getView().findViewById(R.id.name);
tv1.setText("Name : " + object.getString("name"));
tv2=(TextView)getView().findViewById(R.id.birthday);
tv2.setText("BirthDay : " + object.getString("birthday"));
tv3=(TextView)getView().findViewById(R.id.id);
tv3.setText("link : " + object.getString("link"));
String id=object.getString("id");
Bitmap mBitmap = getFacebookProfilePicture(id);
img.setImageBitmap(mBitmap);
/*Toast.makeText(getActivity().getApplicationContext(), object.getString("name") + object.getString("birthday") +object.getString("link")
, Toast.LENGTH_SHORT).show();*/
}catch (JSONException e){
e.printStackTrace();
}
}
});
Bundle parameters= new Bundle();
parameters.putString("fields","name,birthday,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
public Bitmap getFacebookProfilePicture(String userID) {
Bitmap bitmap = null;
try {
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection()
.getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
Everything you can get.Here is code.
private CallbackManager callbackManager;
private LoginButton loginButton;
in OnCreate(){
loginButton = (LoginButton) findViewById(R.id.login_button);
// don't forget to give this.
loginButton.setReadPermissions(Arrays.asList("public_profile,email,user_birthday"));
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDetails();
}
});
}
private void getDetails() {
//for facebook
// FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
//register callback object for facebook result
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String facebook_id = profile.getId();
String f_name = profile.getFirstName();
String l_name = profile.getLastName();
profile_image = profile.getProfilePictureUri(400, 400).toString();
}
String email_id = jsonObject.getString("email"); //email id
} catch (JSONException e) {
Logger.logError(e);
}
}
});
This surely works.
Check whether you are using this.
com.facebook.android:facebook-android-sdk:4.0.0
For a quick solution you can get profile picture of user with:
String profilePictureUrl = "https://graph.facebook.com/"+userID+"/picture?width=500&height=500";
And download with your image loader library to your image view.
Edit:
This is a simple ImageLoading library for Android (old but good)
https://github.com/nostra13/Android-Universal-Image-Loader
Easy to use:
Add it to your project as a gradle dependency.
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(profilePictureUrl, yourImageView);
I am using like :
public void getUserDetailsFromFB(AccessToken accessToken) {
GraphRequest req=GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(),"graph request completed",Toast.LENGTH_SHORT).show();
try{
String email = object.getString("email");
String birthday = object.getString("birthday");
String gender = object.getString("gender");
String name = object.getString("name");
String id = object.getString("id");
String photourl =object.getJSONObject("picture").getJSONObject("data").getString("url");
}catch (JSONException e)
{
Toast.makeText(getApplicationContext(),"graph request error : "+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(large)");
req.setParameters(parameters);
req.executeAsync();
}
Then use Picasso like : Picasso.with(context).load(photourl).into(imageView);
Example Json format here :
{
"id": "10204968538960870",
"name": "Yasin KaƧmaz",
"email": "yasin_5775#hotmail.com",
"gender": "male",
"birthday": "12/06/1994",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0..."
}
}
}
You can try Graph Api to see example Json format in : Graph Api Explorer

In Android, Facebook API V2.4 is not returning email id whereas V2.3 is returning. How to get email id in V2.4?

When I wrote the following code for API V2.3 this was giving me all details including email id. And now the same code is not giving me email id. What can I can do to get email id?
oncreate(..)
{
.
.
EMAIL_PERMISSION = new ArrayList<String>();
EMAIL_PERMISSION.add("email");
uiLifecycleHelper = new UiLifecycleHelper(this, statusCallback);
uiLifecycleHelper.onCreate(savedInstanceState);
Session.openActiveSession(this, true, EMAIL_PERMISSION,
statusCallback);
// callback when session changes state
Session.StatusCallback statusCallback = new StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception
exception)
{
// Checking whether the session is opened or not
if (state.isOpened())
{
} else
{
if (state.isClosed())
{
}
Log.d(TAG, state.toString());
}
}
};
// Method to get user facebook profile
void getUserFacebookProfile(Session session, final boolean finish)
{
// Checking whether the session is opened or not
if (session.isOpened())
{
// Sending request to the facebook to get user facebook profile
Request.newMeRequest(session, new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
// To get network user id
String networkUserid = user.getId();
// To get user first name
String fname = user.getFirstName();
// To get user last name
String lname = user.getLastName();
// To get user middle name
String mname = user.getMiddleName();
// String email = user.getProperty("email").toString();
String email = response.getGraphObject().getProperty("email")
.toString();
}
Now the above code gave me all details including email id for V2.3, now i'm not able to get email id. Please let me know solution. Thanks.
public class LoginFacebook {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
public void openFB() {
LoginManager.getInstance().logInWithReadPermissions(activity,
Arrays.asList("read_stream", "user_photos", "email", "user_location"));
// Login Callback registration
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
new GraphRequest(AccessToken.getCurrentAccessToken(),
"/me", null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(
GraphResponse response) {
/* handle the result */
try {
//GET USER INFORMATION
JSONObject json = response.getJSONObject();
String email = json.getString("email");
String fullName = json.getString("name");
String accessToken = loginResult.getAccessToken().getToken();
int type = 1;
String lastUpdate = json.getString("updated_time");
String user_id = json.getString("id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
GetSnsPost getSnsPost = GetSnsPost.getInstance(activity);
getSnsPost.getFacebookPosts();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
public void loginFacebook(View v){
openFB();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Since session have been deprecated long time ago, I don't use it anymore. I get user information this way. Hope this code will solve your problem ;)
Bundle params = new Bundle();
params.putString("fields", "id,name,email,birthday,first_name,last_name");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
AccessToken.getCurrentAccessToken().getUserId(),
params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(
GraphResponse response) {
System.out.println("\n J S O N :"
+ response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();

Issue getting Facebook information

I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.

Twitter How to get user profile pic using Fabric plugin in Android Studio

I am using Fabric plugin with Android studio after login I got session, username and userid. Also got email address. But can't find any option to fetch user profile pic.
/
/inti twitter client
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
System.out.println("twitter success"+result.data.getUserId()+result.data.getUserName());
gettwitteremail();
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
private void gettwitteremail(){
TwitterSession session =
Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback() {
#Override
public void success(Result result) {
// Do something with the result, which provides
// the email address
System.out.println("twitter sucess"+result.data);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println("twitter sucess"+exception.getMessage());
exception.printStackTrace();
}
});
Fixed
Fixed by using following code
TwitterSession session =
Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
TwitterApiClient twitterApiClient = Twitter.getApiClient();
StatusesService twapiclient = twitterApiClient.getStatusesService();
twapiclient.userTimeline(twitteruserid,null,null,null,null,null,null,null,null,new Callback<List<Tweet>>() {
#Override
public void success(Result<List<Tweet>> listResult) {
System.out.println("listResult"+listResult.data.size());
System.out.println("listResult"+listResult.data.get(0).user);
System.out.println("listResult"+listResult.data.get(0).user.profileImageUrl);
userInfo.imageurl = listResult.data.get(0).user.profileImageUrl;
}
#Override
public void failure(TwitterException e) {
}
});
Try this code for fetch user profile pic.
public void getTwitterData(final TwitterSession session) {
MyTwitterApiClient tapiclient = new MyTwitterApiClient(session);
tapiclient.getCustomService().show(session.getUserId(),
new Callback<User>() {
#Override
public void success(Result<User> result) {
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
name.setText(result.data.name);
location.setText(result.data.location);
new ImageDownloader(profileImageView)
.execute(result.data.profileImageUrl);
Log.d("Name", name);
Log.d("city", location);
}
public void failure(TwitterException exception) {
// Do something on failure
exception.printStackTrace();
}
});
****************
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {
#GET("/1.1/users/show.json")
void show(#Query("user_id") long id, Callback<User> cb);
}
************
class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public ImageDownloader(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

Categories

Resources