Get facebook user profile data, android? - android

I have integrated facebook login in my app. It works fine and in the callback method I get
This is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
findViewById(R.id.sign_in_button).setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("basic_info","user_friends","email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.e("res",""+loginResult.getAccessToken());
Toast.makeText(LoginActivity.this,""+loginResult.getAccessToken().getUserId(),Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
When I print the access token I get
{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[user_friends, contact_email, email, public_profile, basic_info]}
I was looking for on how to get the user's data from FB PROFILE DATA
The method
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
But it asks for a seesion. From where do I get the session?

You can use available info, after the login, using Profile class.
Profile.getCurrentProfile() //get current instance of logged profile
Profile.getCurrentProfile().getId() //get current id
Profile.getCurrentProfile().getName() //get current user name
More about it, in documentation.

Here is complete code with status call back and session handling..
public class LoginFragment extends Fragment {
private LoginButton facebookButton;
private UiLifecycleHelper uiHelper;
//use this
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
try {
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
if (pDialog != null) {
onSessionStateChange(session, session.getState(), null);
}
}
uiHelper.onResume();
} catch (Exception e) {
Log.e(Constants.TAG_EXCEPTION, e.toString());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
public void showLoggedInUserInfo(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
fbFirstName = user.getFirstName();
fbLastName = user.getLastName();
fbEmail = user.asMap().get("email").toString();
}
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
showLoggedInUserInfo(session);
} else if (state.isClosed()) {
// Logged out
}
}
});
request.executeAsync();
}

Related

How to get Facebook user gender , email, phone number details

public class FacebookLoginActivity extends ActionBarActivity {
private List<String> permissions = new ArrayList<String>();
// FaceBook
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private Button facebook_sigin;
private TextView name, email, gender, phone, address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb);
name = (TextView) findViewById(R.id.textView1);
gender = (TextView) findViewById(R.id.gender);
phone = (TextView) findViewById(R.id.phone);
address = (TextView) findViewById(R.id.address);
facebook_sigin = (Button) findViewById(R.id.facebooksigin);
permissions.add("email");
permissions.add("gender");
permissions.add("address");
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
facebook_sigin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (UtillClass.isConnectingToInternet(FacebookLoginActivity.this)) {
Session session = Session.getActiveSession();
if (session != null && !session.isOpened()
&& !session.isClosed()) {
Log.e("facebook login", "1");
Session.OpenRequest request = new Session.OpenRequest(
FacebookLoginActivity.this);
request.setPermissions(permissions);
request.setCallback(statusCallback);
session.openForRead(request);
} else {
Log.e("facebook login", "2");
Session.openActiveSession(FacebookLoginActivity.this, true,
statusCallback);
}
}
}
});
Session session = Session.getActiveSession();
if (session == null) {
if (session == null) {
session = new Session(this);
session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));
}
Session.setActiveSession(session);
}
}
public class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(final Session session, SessionState state,
Exception exception) {
Request request = new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.e("Facebook Response ", "Response==>"+response);
Log.e("Facebook Login ", "onCompleted");
Log.e("session", "" + session.getAccessToken());
try {
JSONObject userDetails = response
.getGraphObject().getInnerJSONObject();
Log.e("fblogijsnresponse",userDetails.toString());
Log.e("facebook user id=",
userDetails.getString("id"));
if (userDetails.has("name")) {
Log.e("facebook user name=",
userDetails.getString("name"));
name.setText(userDetails.getString("name"));
}
if (userDetails.has("first_name")) {
Log.e("fbuserfname=", userDetails.getString("first_name"));
}
if (userDetails.has("last_name")) {
Log.e("fbuserlname=",userDetails.getString("last_name"));
}
if (userDetails.has("gender")) {
Log.e("fbgender","fbgender");
Log.e("fbgender=",userDetails.getString("gender"));
gender.setText(userDetails.getString("gender"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
request.executeAsync();
}
}
#Override
public void onStart() {
super.onStart();
Log.e("facebook", "onStart");
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Log.e("facebook", "onStop");
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e("facebook", "onSaveInstanceState");
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
#Override
public void onBackPressed() {
super.onBackPressed();
// goBack();
}
}
I tried to get facebook user gender ,email, phone and address detail. Can any please help me to find out those details. The above code i have added the permissions for gender , email, address but in facebook response have only facebook user name. I didn't whether we can get all details are not please help me solve this.
Please define permission in that manner.
your_fb_button.setReadPermissions("user_friends");
your_fb_button.setReadPermissions("public_profile");
your_fb_button.setReadPermissions("email");
your_fb_button.setReadPermissions("user_birthday");
for more details please follow this example: Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

Facebook Profile.getCurrentProfile() is always returns null after the first login

For the first time when I login into the app through Facebook, I'm getting profile from Profile.getCurrentProfile();
Where as when I exit the app and launch again, It was already logged in. So I can call directly Profile.getCurrentProfile(); is returning null.
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_page);
Profile profile = Profile.getCurrentProfile();
// For the first launch the profile will be null
displayProfileName(profile);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile");
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile, Profile currentProfile) {
profileTracker.stopTracking();
Profile.setCurrentProfile(currentProfile);
Profile profile = Profile.getCurrentProfile();
displayProfileName(profile);
}
};
profileTracker.startTracking();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (profileTracker != null) {
profileTracker.stopTracking();
}
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
#Override
protected void onRestart() {
super.onRestart();
AppEventsLogger.activateApp(this);
}
/**
*
* Method to display the Profile Name
*/
private void displayProfileName(Profile profile) {
if (profile != null) {
Toast.makeText(MainActivity.this, profile.getName(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "No Profile", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
callbackManager.onActivityResult(arg0, arg1, arg2);
}
There are two cases in this:
For first login, follow my other answer.
For second login, you will need to refresh your AccessToken and then fetch the profile. Refreshing token code can be found in this answer but the code below has it (for simplification).
The code is taken from FB's dreadful documentation).
You can put this code straight into your app, where the comment says "case 1", just invoke your normal FB login.
private AccessTokenTracker mAccessTokenTracker;
private void loginToMyFbApp() {
FacebookSdk.sdkInitialize(this);
if (AccessToken.getCurrentAccessToken() != null) {
mAccessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
mAccessTokenTracker.stopTracking();
if(currentAccessToken == null) {
//(the user has revoked your permissions -
//by going to his settings and deleted your app)
//do the simple login to FaceBook
//case 1
}
else {
//you've got the new access token now.
//AccessToken.getToken() could be same for both
//parameters but you should only use "currentAccessToken"
//case 2
fetchProfile();
}
}
};
mAccessTokenTracker.startTracking();
AccessToken.refreshCurrentAccessTokenAsync();
}
else {
//do the simple login to FaceBook
//case 1
}
}
private void fetchProfile() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// this is where you should have the profile
Log.v("fetched info", object.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link"); //write the fields you need
request.setParameters(parameters);
request.executeAsync();
}
Instead of accessing Profile.getCurrentProfile()
use access token and make graph request in onSuccess()
( It worked for me)
here snippet of code :
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.v("profile track", (DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(loginResult.getAccessToken().getExpires())));
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String name = object.getString("name");
String email = object.getString("email");
String id = object.getString("id");
Toast.makeText(Login.this, name + " " + " " + email + " " + id, Toast.LENGTH_SHORT).show();
/*write your code that is to be executed after successful login*/
} 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() {
}
#Override
public void onError(FacebookException e) {
}
};
Call LoginManager.getInstance().logOut(); once you get the profile details.

How to get the email of a user from the facebook LoginButton widget?

How can I get the email of a user from the facebook LoginButton widget?
I am getting null. The App Id I am using is correct. I can also get the correct name, but the email is missing. I do have permissions.
This is my code:
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
// ...
public class MainActivity extends FragmentActivity {
// ...
#Override
public void onCreate(Bundle savedInstanceState) {
//
LoginButton loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
Toast.makeText(getApplicationContext(),
"User Name is , " + user.getName(), Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
"Email Id is , " + user.getProperty("email") , Toast.LENGTH_LONG)
.show();
} else {
userName.setText("You are not logged");
}
}
});
}
// ...
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","email","basic_info");
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
public class Login extends ActionBarActivity {
private CallbackManager callbackManager;
String emailid, gender, bday, username;
private LoginButton loginButton;
ProfilePictureView profilePictureView;
TextView info;
private AccessTokenTracker accessTokenTracker;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login);
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) {
new fblogin().execute(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
class fblogin extends AsyncTask<AccessToken, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("wait.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(AccessToken... params) {
GraphRequest request = GraphRequest.newMeRequest(params[0],
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
username = object.getString("first_name");
emailid = object.getString("email");
gender = object.getString("gender");
bday = object.getString("birthday");
} catch (JSONException e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,first_name,email,gender,birthday");
request.setParameters(parameters);
request.executeAndWait();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
This method work in Async manner.
Its Done . !!
You can fetch user email by sending Request.newMeRequest request. For this you need UiLifecycleHelper callback
UiLifecycleHelper fbUiHelper = new UiLifecycleHelper(this, fbUiHelperCallback);
private Session.StatusCallback fbUiHelperCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
getUserData(session, state);
}
private void getUserData(Session session, SessionState state) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String name = user.getName();
// If you asked for email permission
String gender = (String) user.getProperty("gender");
String email = (String) user.getProperty("email");
}
}
}).executeAsync();
}
}

Login With Facebook without Login Button Android

hi here i am creating login with facebook without login button. it is work properly but at the closing facbook webkit login form it is again open pop up for request permission continuously. give me solution for it.
private void FacebookLogin() {
// TODO Auto-generated method stub
final Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, Arrays.asList("email"));
Session openActiveSession = Session.openActiveSession(this, true,
new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
session.requestNewReadPermissions(newPermissionsRequest);
Request getMe = Request.newMeRequest(session,
new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
org.json.JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String email = graphResponse
.optString("email");
String id = graphResponse
.optString("id");
}
}
});
getMe.executeAsync();
} else {
if (!session.isOpened())
Log.d("FACEBOOK", "!session.isOpened()");
else
Log.d("FACEBOOK", "isFetching");
}
}
});
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
Session.getActiveSession().onActivityResult(this, arg0, arg1, arg2);
}
I found two methods.
The first - you add into XML facebook button and hide (set visability = GONE) it. Initialize this button and on you custom event call facebookButton.performClick();
Second way - use this part of code:
callbackManager = CallbackManager.Factory.create();
List<String> permission = new ArrayList<String>();
permission.add("email");
LoginManager loginManager = LoginManager.getInstance();
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if (facebookDialog.isShowing()) {
loadingProgressBar.setVisibility(View.VISIBLE);
singViaFacebook.setText(R.string.dialog_facebook_loggin);
}
loadProfile();
}
#Override
public void onCancel() {
lockLoginButton(true);
startTimer();
}
#Override
public void onError(FacebookException exception) {
lockLoginButton(true);
startTimer();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
And call this piece of code when you want call popup:
loginManager.logInWithReadPermissions(this, permission)
Works with Facebook SDK [4,5)
First Declare Callback manager like,
private CallbackManager callbackManager;
private AccessToken accessToken;
put this code in OnCreate()::
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
getFacebookUserProfile(accessToken);
}
#Override
public void onCancel() {
Toast.makeText(StartUpActivity.this, "Login with facebook canceled.", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(StartUpActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Then assign click to your button like,
btnFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
getFacebookUserProfile(accessToken);
} else {
LoginManager.getInstance().logInWithReadPermissions(StartUpActivity.this, Arrays.asList("public_profile", "email"));
}
}
});
Then Override,
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CallbackManagerImpl.RequestCodeOffset.Login.toRequestCode()) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Then use this function for get user profile,
private void getFacebookUserProfile(AccessToken accessToken) {
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
authenticateUser(object);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, first_name,last_name, email");
request.setParameters(parameters);
request.executeAsync();
}
Hope it works for you
Try this
public class LoginFragment extends Fragment{
boolean isFetching = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, null);
Button button = (Button) view.findViewById(R.id.login_button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
performFacebookLogin();
}
});
return view;
}
private void performFacebookLogin()
{
Log.d("FACEBOOK", "performFacebookLogin");
final Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(getActivity(), Arrays.asList("email"));
Session openActiveSession = Session.openActiveSession(getActivity(), true, new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
Log.d("FACEBOOK", "call");
if (session.isOpened() && !isFetching)
{
Log.d("FACEBOOK", "if (session.isOpened() && !isFetching)");
isFetching = true;
session.requestNewReadPermissions(newPermissionsRequest);
Request getMe = Request.newMeRequest(session, new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
Log.d("FACEBOOK", "onCompleted");
if (user != null)
{
Log.d("FACEBOOK", "user != null");
org.json.JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String email = graphResponse.optString("email");
String id = graphResponse.optString("id");
String facebookName = user.getUsername();
if (email == null || email.length() < 0)
{
Toast.makeText(getActivity(),
"An email address is required for your account, we could not find an email associated with this Facebook account. Please associate a email with this account or login the oldskool way.", Toast.LENGTH_LONG).show();
return;
}
}
}
});
getMe.executeAsync();
}
else
{
if (!session.isOpened())
Log.d("FACEBOOK", "!session.isOpened()");
else
Log.d("FACEBOOK", "isFetching");
}
}
});
}
}
Now add a button in your fragments layout
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login With Facebook" />
It works for me , and only once pop up the request permission try it and let me know

Can not add a publish_stream permission

Hi I tryed to add public_stream permission in my app. I put to print my session iformation in my consol and I observ that when I add the public permission my session state is CLOSED_LOGIN_FAILED, and when I removed this permission the session state in OPENING and I have set the other read permission.
This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.facebook_login_view, container,
false);
facebookButton = (LoginButton) view.findViewById(R.id.facebookAuth);
facebookButton.setFragment(LoginAuthFragment.this);
//facebookButton.setReadPermissions("email", "user_birthday");
facebookButton.setPublishPermissions("publish_stream", "email", "user_birthday");
return view;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
System.out.println(session);
System.out.println("Access token: "+session.getAccessToken());
final User u = new User();
if(session.isOpened()){
System.out.println("OK");
final String subscribe;
if(receiveMail.isChecked()){
subscribe = "1";
}else{
subscribe = "0";
}
final String access_token=session.getAccessToken();
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String userName = "fb_user_"+user.getId();
String facebook_id = user.getId();
String birthday = user.getBirthday();
String email = user.asMap().get("email")
.toString();
String response1 = u.checkFacebookUser(
userName, facebook_id, access_token,
birthday, email, subscribe, firstName, lastName);
if (response1.equals("GREEN")) {
prefs.setTokenData(u.getToken(),
u.getCreatedAt(), u.getExpires());
Intent loggedIn = new Intent(getActivity().getApplicationContext(),
MainActivity.class);
startActivity(loggedIn);
getActivity().finish();
} else if (response1.equals("RED")) {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Unknown error", Toast.LENGTH_LONG)
.show();
}
}
}
});
Request.executeBatchAsync(request);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
And here is my session when I add publish_stream permission
{Session state:CLOSED_LOGIN_FAILED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:593058290740634}
And here is my session without publish_stream permission:
{Session state:OPENED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[email, user_birthday, user_friends, basic_info]}, appId:593058290740634}
You cannot request publish permissions without first getting "basic_info" (which is a read permission).
The correct course of action is to first ask the user for email and user_birthday permissions, and when you're ready to publish (usually after some user interaction), then ask for publish_stream permissions.

Categories

Resources