How to have Access Token Facebook SDK 4.4.1 - android

I want to use Facebook SDK to get my photo's url, and display it. I log in with fb sdk, but each time I open my app, I must log out and log in again to have access token. Can I have acces token without log in fb? And can I have access token of my friend's page? Please help me.
This is my code:
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private ImageView image;
private LoginButton loginButton;
private AccessToken accessToken;
JSONObject jsObject = null;
public MyAsyncTask myAsy;
public String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_photos"));
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// Get images's url code
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "photos{images}");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// info.setText("Login attempt cancelled.");
}
#Override
public void onError(FacebookException e) {
// info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}

1) No, you can't get a user access token without first logging the user in. Access tokens have an expiry time and have to be renewed/re-issued from time to time.
2) If by "can I get an access token for a friend's page" mean if you can get an access token for a friend without said friend doing anything, then no, you can't. You need to have that friend login to your app just like every other user.

Related

Unable to get Email via Facebook login

Unable to get email via Facebook login though we get accesstoken, id , name but email as null even permission for email is also mentioned in code,is there anything we have set permission for email too from facebook developer console.
Followed the set as per the developers.facebook.com,.
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
private static final String EMAIL = "email";
String Email = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
//loginButton.setReadPermissions(Arrays.asList(EMAIL));
// If you are using in a fragment, call loginButton.setFragment(this);
// Callback registration
LoginManager loginManager = LoginManager.getInstance();
loginManager.logInWithReadPermissions(MainActivity .this, Arrays.asList(EMAIL));
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.e("Facebook_loginResult", loginResult.getAccessToken().getToken());
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.e("Login_FB_Response", object.toString());
if (object.has("email")) {
Email = object.getString("email");
}
Log.e("Login_FB_Email", Email);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, birthday, gender, location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.e("Facebook_Cancel", "onCancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook_Exception", exception.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}}

Login with Facebook with Dialog in Android

How to implement this login with facebook?
I've followed this tutorial https://www.androidlearning.in/facebook-login-for-android-app/ but it throws a complete activity (the traditional way).
I have facebook application installed
In applications like Memrise, Bandlab, etc. Shows me that Dialog but no in my application
Also I try with
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList([...]);
but dont works...
I want:
My app Show me:
I was facing the same problem as you 30 minutes ago, but I was using a custom button for Facebook and the following code inside onCreate for calling Facebook Login:
loginButton = (CircularProgressButton) findViewById(R.id.btn_fb);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
}
});
//Register a callback
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
try {
nome = object.getString("name");
email = object.getString("email");
String idfb = loginResult.getAccessToken().getUserId();
logarFb(idfb, nome, email);
} catch(JSONException ex) {
ex.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
//cancelled
}
#Override
public void onError(FacebookException exception) {
//error
}
});
I changed it to Facebook Login button:
<com.facebook.login.widget.LoginButton
android:id="#+id/btn_fb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
Now that's how my code looks like now, much cleaner:
private LoginButton loginButton;
private CallbackManager callbackManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
loginButton = findViewById(R.id.btn_fb);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
#Override
public void onCancel() {
funcoes.aviso(MainActivity.this,"Você cancelou o login",R.color.red500,3000, R.drawable.ic_triste);
}
#Override
public void onError(FacebookException exception) {
funcoes.dialogoMsg(MainActivity.this,"Há algo de errado com o login do Facebook :/");
}
});
}
protected void getUserDetails(final LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted( JSONObject object, GraphResponse response) {
try {
nome = object.getString("name");
email = object.getString("email");
String idfb = loginResult.getAccessToken().getUserId();
logarFb(idfb, nome, email);
} catch(JSONException ex) {
ex.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
data_request.setParameters(parameters);
data_request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
If do you have Facebook App installed, that's should be enough to have the Facebook Login as Dialog Box instead of an FullScreen Activity.
If you want so, follow this guide If you forgot some other setting: https://www.studytutorial.in/android-facebook-integration-and-login-tutorial
The dialog will appear only if you have the facebook app installed on your phone , other wise you will get a web view. Try installing the app and then logging in.
You need to remove the permission "user_birthday" If you defined in your permissions.
LoginManager.getInstance().logInWithReadPermissions(context,Arrays.asList("public_profile","email"));
As some permissions needs for "App Review"
I have changed my permission set
Existing code
LoginManager.getInstance().logInWithReadPermissions(activity, listOf("user_photos", "email", "public_profile"))
Working code
LoginManager.getInstance().logInWithReadPermissions(activity, listOf("email"))

Facebook Profile getName() on Android always returning null

My Facebook Login Activity if it helps:
public class LoginActivity extends AppCompatActivity {
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "user_friends");
final Intent myIntent = new Intent(this, MapsActivity.class);
if (isLoggedIn()) {
startActivity(myIntent);
finish();
return;
}
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "user_friends"));
startActivity(myIntent);
finish();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
});
}
private boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
}
and the code I'm using to attempt to get someone's first name from their ID:
new Profile(creatorId, null, null, null, null, null).getFirstName()
I have tried the getFirstName() call shown here in addition to getName() and both always return null. I thought having "public_profile" in my requested Facebook permissions would allow me to get someone's name in this way if they have authorized my app while logging in through Facebook. However, I did not always have "public_profile" in my requested Facebook permissions, but I have forced all users to re-login through Facebook to my app with this current code and permissions, so I thought this would fix this problem. Nevertheless, this function keeps returning null and I'm not sure why.
Also, creatorId may be the FB ID of a different user than the currently logged in FB user. (They will have authorized+used the app in the past, just not the currently logged in user on that Android device).
So, it seems that a Graph Request is necessary, even for public profile information. Here is the Graph Request I used to get the first name for a certain Facebook ID, creatorId:
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
creatorId,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
Log.e("creatorId's first name:", response.getJSONObject().getString("first_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle params = new Bundle();
params.putString("fields", "id,first_name");
request.setParameters(params);
request.executeAsync();
You can use this code.
please change your GraphRequest.GraphJSONObjectCallback() interface
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
try {
Log.e(TAG,"id"+user.optString("id"));
Log.e(TAG,"id"+user.optString("first_name"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name");
request.setParameters(parameters);
request.executeAsync();`

Android Facebook SDK 4.0 Login without Facebook App

I'm having issues with the webview login for Facebook on Android.
I've followed the tutorials and login works perfectly when the user has the Facebook app installed. When the Facebook app is not installed, the webview for facebook login pops up; however, after logging in and accepting the permissions, the webview simply redirects back to the login screen. It never goes back to my app.
Has anyone else encountered this problem?
FacebookSdk.sdkInitialize(this);
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
if (profile2 != null) {
loggedIn(profile2);
} else {
loggedOut();
}
}
};
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
Profile.fetchProfileForCurrentAccessToken();
}
};
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
getProfileInfo();
}
#Override
public void onCancel() {
// App code
Log.e("Facebook Login", "Login Cancelled");
loggedOut();
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook Login", "Failed to Login " + exception.toString());
loggedOut();
}
});
Looking at the logs without filters while the login takes place, I see a couple of possibly relevant logs.
I/chromium﹕ [INFO:CONSOLE(0)] "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.", source: (0)
I/Auth.Core﹕ [TokenCache] Missing snowballing token: no granted scopes set.
What was causing the problem was that I was overriding the onclicklistener of the login button to call the login function of the LoginManager. Just don't.
I think you forgot to use callbackManager for proper workflow. Used CallbackManager for registration callback must be called in onActivityResult of host activity. Activity should not be in singleInstance launchMode because it will not be able to launch startActivityForResult(facebook internally launches FacebookActivity using this method).
So add to your activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Given your description, I am imagining that you either are not connected on the internet or that you are not handling the login callbacks.
Here is a full facebook 4.0.+ login example.
Edit Based on your code:
You need to use FacebookSdk.sdkInitialize(this); before setContentView().
This is a working example without using Facebook app and if you close your app and open it again you'll be logged in automatically unless you log out.
Here we get the user email address and friends list after log in.
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private static final String TAG = "logTag";
private TextView mFriend, mEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
mFriend = (TextView) findViewById(R.id.tv_friend);
mEmail = (TextView) findViewById(R.id.tv_email);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "Successful Login");
GraphRequest friendsRequest = GraphRequest.newMyFriendsRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray objects, GraphResponse response) {
String x = objects.opt(0).toString();
mFriend.setText(x);
}
});
GraphRequest meRequest = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = response.getJSONObject().getString("email").toString();
mEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email, gender");
meRequest.setParameters(parameters);
meRequest.executeAsync();
parameters = new Bundle();
parameters.putString("field", "user_friends");
friendsRequest.setParameters(parameters);
friendsRequest.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "Login Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "Login Error");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// manage login results
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Response code 200 from facebook

I'm developing new android app which uses facebook sdk. I want to fetch users friends list, I'm doing it like that:
Request request = Request.newMyFriendsRequest(
Session.getActiveSession(),
new Request.GraphUserListCallback() {
public void onCompleted(List<GraphUser> paramAnonymousList,
Response paramAnonymousResponse) {
Toast.makeText(getApplicationContext(),
paramAnonymousList.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, paramAnonymousList.toString()
+ paramAnonymousResponse.toString());
}
});
request.executeAsync();
However when I run app I'm getting something like that:
GraphObjectList{itemType=GraphUser, state=[]}{Response: responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[]}}, error: null, isFromCache:false}
I tried to run this code inside app which is not in development mode and it's working fine - i'm able to fetch user's data. What can be the cause of response code 200. According to that: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0 response code 200 belong to facebook permission errors. But to fetch user's friends list I don't have to provide any specific permissions, so what can be the cause of this response?
Thanks in advance
HTTP 200 means that your request is OK.
The real issue is Facebook API v2.0. Apps cannot retrieve the full list of friends for a user, only friends already using the application. Even if you application is still in v1.0, users who first logged in after May 1st are getting v2.0 behaviour.
Reference: https://developers.facebook.com/docs/graph-api/reference/v2.0/user/friends
Cheers!
I have done in this way and works fine perfectly in Facebook SDK 4.18.0
public class SignIn extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//before set conteview
FacebookSdk.sdkInitialize(getApplicationContext());
// AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_signin);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest graphRequest=GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
Log.d("Graph Response",graphResponse.toString());
String myCustomizedResponse = graphResponse.getJSONObject().toString();
Log.d("Ketan_Ramani",graphResponse.getJSONObject().toString());
try {
JSONObject obj = new JSONObject(myCustomizedResponse);
String id = obj.getString("id");
String first_name = obj.getString("first_name");
String last_name = obj.getString("last_name");
String email = obj.getString("email");
Log.d("Id",id);
Log.d("FirstName",first_name);
Log.d("LastName",last_name);
Log.d("Email",email);
} catch (JSONException e) {
Utils.hide_dialog();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Categories

Resources