Am trying do display the profile picture of a user who has signed in to my app.This is a simple app that just signs someone in, and starts a logout activity upon successful login.In the logout activity, am trying to display a welcome message and the picture of the user.So far I've got the welcome message to work by defining the onConnected() method in the MainActivity as so:
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
Intent startLogoutActivityIntent = new Intent(this, LogoutActivity.class);
startLogoutActivityIntent.putExtra("ACCOUNT_NAME", accountName);
if (mPlusClient.getCurrentPerson() != null) {
Person currentPerson = mPlusClient.getCurrentPerson();
String personName = currentPerson.getDisplayName();
String photo = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
startLogoutActivityIntent.putExtra("Profile_photo", photo);
}
startActivity(startLogoutActivityIntent);
}
and in my LogoutActivity class i added these lines
TextView message = (TextView) findViewById(R.id.welcomeMessage);
message.setText("Welcome to the DivingScores app " + in.getStringExtra
("ACCOUNT_NAME"));
ImageView profilePicture = (ImageView) findViewById(R.id.userImage);
The problem is i don't know what method to call with profilePicture. I have tried
profilePicture.setImageResource(in.getStringExtra("profile_photo")); but i get the error
setImageResource (int) in ImageView cannot be applied to (java.lang.String).
Can someone please point me in the right direction?
in.getStringExtra("profile_photo");
You are receiving a url to the profile image, so you should download the image from that url and then set that image to the Imageview.
Have a look here :
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
http://theopentutorials.com/tutorials/android/imageview/android-how-to-load-image-from-url-in-imageview/
That should help you display the image after fetching the url
Related
I might me doing something wrong. I managed to get the facebook image with user.getPhotoUrl but it only shows a low res picture.
So I tried using this code.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String name = user.getDisplayName();
nameView.setText(user.getDisplayName());
Picasso.with(this).load("https://graph.facebook.com/"+user.getUid()+"/picture?type=large").into(profileImage);
}
What am I doing wrong here?
Use this link to get a picture of a quality that you want. Just replace width=200 with the width you want and height=200 with the height you want.
"https://graph.facebook.com/"+user.getUid()+"/picture?type=large&width=200&height=200"
I managed to do it!
for(UserInfo profile : user.getProviderData()) {
if(profile.getProviderId().equals(getString("facebook.com"))) {
facebookUserId = profile.getUid();
}
}
String photoUrl = "https://graph.facebook.com/" + facebookUserId + "/picture?height=500";
Picasso.with(this).load(photoUrl).into(profileImage);
This worked for me
I have added Firebase Auth in my android app and I am using Facebook and Google sign in. Signing in is working fine. Now I want to retrieve user profile info from user's either Facebook account or Google account (whichever, user chooses to sign in) and display the info in user profile activity. I am able to retrieve and display user name and user UID, however, user email and user photo are not displaying, though retrieved.
Here is how I am retrieving user info (LoginActivity.java):
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
for (UserInfo userInfo : user.getProviderData()){
String user_name = userInfo.getDisplayName();
String user_email = userInfo.getEmail();
Uri user_img = userInfo.getPhotoUrl();
String user_id = userInfo.getUid();
SharedPreferences preferences = getSharedPreferences(UserInfoConstants.STRING_NAME,0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(UserInfoConstants.KEY_USER_NAME, user_name);
editor.putString(UserInfoConstants.KEY_USER_EMAIL, user_email);
editor.putString(UserInfoConstants.KEY_USER_ID, user_id);
editor.putString(UserInfoConstants.KEY_USER_IMG, user_img != null ? user_img.toString() : null);
editor.apply();
}
} else {
//User is signed out
return;
}
}
};
Here is how am displaying user info (ProfileActivity.java):
SharedPreferences preferences = getSharedPreferences(LoginActivity.UserInfoConstants.STRING_NAME,0);
String user_img_uri = preferences.getString(LoginActivity.UserInfoConstants.KEY_USER_IMG,"");
if (user_img_uri.isEmpty()){
userImgView.setImageResource(R.drawable.com_facebook_profile_picture_blank_portrait);
} else {
userImgView.setImageBitmap(getImageBitmap(user_img_uri));
}
userName.setText(preferences.getString(LoginActivity.UserInfoConstants.KEY_USER_NAME,""));
userEmail.setText(preferences.getString(LoginActivity.UserInfoConstants.KEY_USER_EMAIL,""));
userId.setText("ID: " + preferences.getString(LoginActivity.UserInfoConstants.KEY_USER_ID,""));
I searched a lot about it but is unable to get any resolution for the same.
Can anyone help????
Uri refrence is always null. Try to store it as string like this:
String uri = userInfo.getPhotoUrl().toString;
And pass it to preference, then set it like this:
String fbImage = pref.getString("ImageUri", "");
if (fbImage != null && !fbImage.isEmpty()) {
Picasso.with(getApplicationContext())
.load(fbImage)
.placeholder(R.drawable.img_circle_placeholder)
.resize(avatarSize, avatarSize)
.centerCrop()
.transform(new CircleTransformation())
.into(ImageViewObject);
}
Make sure you added picasso dependency to your gradle.
compile 'com.squareup.picasso:picasso:2.3.2'
for emailID:
String email = pref.getString("email", null);
//try to check here
Log.w("email", ""+email);
if(email != null && !email.isEmpty()){
textEmail.setText(""+email);
}
or you can use intent service this is work for sure:
In you login activity:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("email_id", email_id);
startActivity(intent);
finish();
and in your mainActivity:
Intent intent = getIntent();
String email = intent.getStringExtra("email_id");
textEmail.setText(""+email);
update-2
there is one firebase method.. and its easiest way to do it.
write this code in your second activity where you want to retrive data..
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
TextView email;
email.setText(""+ user.getEmail());
there is no need of sharedPrefrence or intent service.
Good afternoon everybody. I'm following this tutorial:
http://www.androidwarriors.com/2015/11/twitter-login-android-studio-example.html
which has this associated GitHub project:
https://github.com/androidwarriors/TwitterLoginUsingFabric
Everything seems to be working, when I get to the lines:
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this).text("test tweet 789");
builder.show();
getUserData();
I am able to see the Toast confirming successful login and then apparently an implicit intent is started, the phone asks which browser I would prefer to use, then opens that browser with "test tweet 789" already entered and a button to send the tweet.
The concern is, I would like to directly send the tweet from my app, rather than bringing up a browser as a separate app to do so. Is there a way to do this? Seems like an easy question and it's probably only another line of code or two but I could not find a directly applicable example, please advise. Sorry if I'm missing something easy here.
For the record here is my entire onCreate method, mostly directly from the tutorial linked above.
///////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv_username);
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
Log.d("Twitter ", "Login sucessfull");
session = result.data;
String username = session.getUserName();
userid = session.getUserId();
textView.setText("Hi " + username);
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this).text("test tweet 789");
builder.show();
getUserData();
}
#Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
}
Silently posting tweets doesn't seem to be part of Fabric's SDK. You may want to look at their REST API.
Am trying to display the profile picture of users logged into my app through Google+ but am not sure how to do this.To get the image (and other information), google provides the code
#Override
public void onConnected() {
...
if (mPlusClient.getCurrentPerson() != null) {
Person currentPerson = mPlusClient.getCurrentPerson();
String personName = currentPerson.getDisplayName();
String personPhoto = currentPerson.getImage();
String personGooglePlusProfile = currentPerson.getUrl();
}
}
I am aware that ordinarily i would need to get any image i want to display from res/drawable... but i don't know what to do with the value of personPhoto (which somehow get's changed from type String to Image when you paste the code in Eclipse.
You need to use that URL to grab the photo as a bitmap and set it to an imageview.
Section 4.9 of this article explains how to make an asynctask that will do just that:
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
First you need to add this dependency in your app/build.gradle file:
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
After this update your UI Accordingly :
private void updateUI(GoogleSignInAccount account) {
if (account != null){
text.setText("Sign in as :" +account.getDisplayName());
email.setText(account.getEmail());
String imgurl = account.getPhotoUrl().toString();
Glide.with(this).load(imgurl).into(profile);
sighIn.setVisibility(View.GONE);
sighOut.setVisibility(View.VISIBLE);
}
else {
text.setText("signOut");
sighIn.setVisibility(View.VISIBLE);
sighOut.setVisibility(View.GONE);
}
}
This is the solution that worked on my Android app. I developed it from an answer above by Naveen Kumar Yadav.
Prerequisites
- I am using a Google Sign-In API for my login.
- I have an XML Code with an ImageView that has an id "client_dp"
Add this dependency to your app-level build.gradle file
dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
Then add this code to your activity java file
//Firebase get user info
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser account = firebaseAuth.getCurrentUser();
if (account != null){
//Display User Image from Google Account
//Objects.requireNonNull() prevents getPhotoUrl() from returning a NullPointerException
String personImage = Objects.requireNonNull(account.getPhotoUrl()).toString();
ImageView userImage = findViewById(R.id.client_dp);
Glide.with(this).load(personImage).into(userImage);
}
With new google sign in Options in Kotlin. Simply request for the parameters you need in your onCreate function
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString("your-client-id"))
.requestEmail()
.requestProfile()
.requestId()
.build()
When recieving back the response from google Sign in activity, inside the
Get user profile picture through:
val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
val photoUrl = credential.photoUrl.toString()
I have created my android code wherein I fetch all the data from facebook and then displays it in a textView and it works just fine on my account. But after I tried to connect with my dummy account, no details is fetched and I don't know the cause of this problem. Well here's my code to review:
private void getFbName() {
mProgress.setMessage("Finalizing ...");
mProgress.show();
new Thread() {
#Override
public void run() {
String name = "";
int what = 1;
try {
String me = mFacebook.request("me");
JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
name = jsonObj.getString("first_name") + "|" + jsonObj.getString("last_name") + "|" + jsonObj.getString("email") + "|" + jsonObj.getString("id");
what = 0;
}
catch (Exception ex) {
ex.printStackTrace();
}
mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name));
}
}.start();
}
private Handler mFbHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgress.dismiss();
if (msg.what == 0) {
String username = (String) msg.obj;
username = (username.equals("")) ? "No Name" : username;
//SPLITTER
String tokens[] = username.split("\\|");
TextView fname = (TextView) findViewById(R.id.textView1);
fname.setText(tokens[0]);
TextView lname = (TextView) findViewById(R.id.textView2);
lname.setText(tokens[1]);
TextView eadd = (TextView) findViewById(R.id.textView3);
eadd.setText(tokens[2]);
TextView fbid = (TextView) findViewById(R.id.textView4);
fbid.setText(tokens[3]);
SessionStore.saveName(username, Main.this);
//mFacebookBtn.setText(" Facebook (" + username + ")");
Toast.makeText(Main.this, "Connected to Facebook as " + username, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(Main.this, "Connected to Facebook", Toast.LENGTH_SHORT).show();
}
}
};
Well I only followed this tutorial for my code with some modification in the design wherein I use 1 button for login and another for logout and then displays the result in 4 textViews.
Edit
Here's my logout code:
private void fbLogout() {
mProgress.setMessage("Disconnecting from Facebook");
mProgress.show();
new Thread() {
#Override public void run() {
SessionStore.clear(Main.this);
int what = 1;
try {
mFacebook.logout(Main.this);
what = 0;
}
catch (Exception ex) {
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
When using the facebook android SDK, you two have two types of authentication:
Using the SDK auth dialog which will ask the user for his email/password.
Using Single Sign-On (SSO) which will only work if the device has the facebook application (katana) installed. If that's the case, that app will be responsible for the authentication which creates a better user experience since the user is already signed in and does not need to reenter his credentials.
If you are following the tutorial then you are using SSO (if the app is installed of course), and because of that when ever you are using the facebook.authorize method you are asking the fb app to authorize your app for the current logged in user.
If you want another user to use your app you'll need the user to log out of the main facebook app.
You can use the sdk authentication and bypass the SSO as suggested here: How to disable Facebook single sign on for android - Facebook-android-sdk, but as I said before, I think it results in a bad user experience.
Another thing is that you keep implementing things using threads, but the facebook android SDK already gives you a helper class for that, it's the AsyncFacebookRunner which makes api requests asynchronously, read Async API Requests.