I am writing an application that needs to use the user data taken from the client social network VKontakte.
I did authorize VKontakte.
VKSdk.initialize(sdkListener, String.valueOf(idVK), VKAccessToken.tokenFromSharedPreferences(this, sTokenKey));
And got AccessToken.
As now I get the name and email user?
You can request email scope from user, then get email from access token:
String email = VKSdk.getAccessToken().email;
String userId = VKSdk.getAccessToken().userId;
//Get user info
VKApi.users().get().executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUser user = ((VKList<VKApiUser>)response.parsedModel).get(0);
Log.d("User name", user.first_name + " " + user.last_name);
}
});
But remember, email is only available after first access request.
Old answer:
You can't get an email. This is not available. But you can get user name:
VKApi.users().get().executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUser user = ((VKList<VKApiUser>)response.parsedModel).get(0);
Log.d("User name", user.first_name + " " + user.last_name);
}
});
For now, you can't get user email.
But you can get other simple info from user profile via class
java.lang.Object
com.vk.sdk.VKObject
com.vk.sdk.api.model.VKApiModel
Here is all available info:
http://vkcom.github.io/vk-android-sdk/com/vk/sdk/api/model/VKUser.html
After login user
I use this code
final VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "photo_200, contacts"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
VKApiUserFull user = ((VKList<VKApiUserFull>)response.parsedModel).get(0);
NavigationHelper.replaceFragment(getActivity().getSupportFragmentManager(), FrHome.newInstance(String.format("%s %s,", user.first_name, user.last_name), user.mobile_phone, user.photo_200), false);
}
});
List fields you can found here
https://vk.com/dev/users.get
Related
setting up the Android Firebase on Android.
I need to get the unique identifier of the user, so that I can have consistency accross all platforms no matter if the email is hided or not.
Based upon https://firebase.google.com/docs/auth/android/apple , using .startActivityForSignInWithProvider(this, provider.build()) we can see:
public void onSuccess(AuthResult authResult) {
Log.d(TAG, "checkPending:onSuccess:" + authResult);
// Get the user profile with authResult.getUser() and
// authResult.getAdditionalUserInfo(), and the ID
// token from Apple with authResult.getCredential().
And from Apple https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple#3383773 we can also see
The identity token is a JSON Web Token (JWT) and contains
and
sub
The subject registered claim identifies the principal that’s the subject of the identity token. Because this token is for your app, the value is the unique identifier for the user.
Question:
What I got from firebase is AuthCredential , but I am expecting JWT with "sub" in it.
How can I get it?
thanks to Ricardo from Firebase support I got this working.
in Android the sub value from Apple is in
"firebase":{"identities":{"apple.com":["001814.24f212edfsdfdfsfd69b7b5fee972e.1722"],"email":["a#b.com"]},"sign_in_provider":"apple.com"}
You get it using
auth.startActivityForSignInWithProvider(this, provider.build()).addOnSuccessListener( new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
// Sign-in successful!
FirebaseUser user = authResult.getUser();
AuthCredential identityToken = authResult.getCredential();
authResult.getUser().getIdToken(false).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
#Override
public void onSuccess(GetTokenResult result) {
String idToken = result.getToken();
//Do whatever
Log.d(TAG, "GetTokenResult result = " + idToken);
try {
decodeJWT(idToken);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
})
Where the JWT is decoded with
private static void decodeJWT(String JWTEncoded) throws Exception {
try {
String[] split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
Log.d("JWT_DECODED", "Body: " + getJson(split[1]));
} catch (UnsupportedEncodingException e) {
//Error
}
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException{
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
I am attempting to the number of friends from facebook authentication api in an android application needed to call facebook permission api. Below is a snippet I am using
fbLoginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
the app fails with a json exception at this line
PUBLICPROFILE = object.getString("public_profile"); //error here
EDITTED - Here is a snippet of my attempt:
Name = object.getString("name");
Email = object.getString("email");
DOB = object.getString("birthday");
DOB = object.getString("birthday");
PUBLICPROFILE = object.getString("/me/friends");
Log.v("Email = ", " " + Email);
Log.v("PUBLIC PROFILE = ", " " + PUBLICPROFILE);
Please does anyone know how I can the number of friends from facebook on android login authentication
As per the facebook developer api /{user-id}/friends
1.the User's friends who have installed the app
2.the User's total number of friends (including those who have not installed the app making the query)
After getting facebook token you can use this implementation
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/{user-id}/friends",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
// Insert your code here
}
});
request.executeAsync();
https://developers.facebook.com/docs/graph-api/reference/user/friends/
I want to share an image on a Facebook page of mine. But I couldn't figure out how to do this step by step. And couldn't find step by step guide for this.
This is my code to share an image on a page
Bundle params = new Bundle();
String nameText = name.getText().toString();
String tags = engine.implodeTags(tagsList);
String textText = text.getText().toString();
params.putString("caption", nameText + "\n\n" + textText + "\n\n" + tags);
params.putString("url", imagesList.get(mainImageSelected).getImageUrl());
params.putString("access_token", "{access token here}");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{page_id here}/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if(response.getJSONObject()!=null) {
Log.d("qwe", response.getJSONObject().toString());
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Shared on facebook", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
else{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
}
).executeAsync();
It works if I put access token by hand. I am getting access token here
https://developers.facebook.com/tools/explorer .
But after some time this access token is not working any more. So I need to get new access token.
How to get PAGE access token from android itself? Via user login button of facebook sdk?
https://developers.facebook.com/docs/facebook-login/access-tokens
Please help.
Easily if you use facebook SDK to do that. read at here https://developers.facebook.com/docs/sharing/android
You need to get Permanent access token to share images on your Page. To get that you need to follow steps written here.
facebook: permanent Page Access Token?
I am trying to integrate Facebook API for login functionality in android. I need email Id for respective user. I am getting JSON in response but It has no email Id.How can I achieve to get the email Id.
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
// Dayanand plzz check this log n let me know.
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is code, Where I am getting null in Toast. It goes to catch method.Please help
You have to ask for the permission : email from the user.
You need to ask for the email permission to the user, otherwise you can't get it.
Once the user grants you the permission, you'll see it when requesting for me.
See http://developers.facebook.com/docs/reference/login/email-permissions/
When you first time login at that time you are passing one permission array. so, you have to pass this array for email permission..
private String[] permissions = {"publish_stream","email","user_about_me","user_status"};
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.