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.
Related
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
I'm able to get all those things as shown in my code below, but unable to retrieve email from the user profile.
What can I do for this?
Any kind of help will be appreciated.
Earlier I was using this source to get details of Facebook user and was fetching data (including Email) without any trouble:
public class MainActivity extends Activity {
private Session.StatusCallback sessionStatusCallback;
private Session currentSession;
private Button login;
private Button logout;
private Button publishButton;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
// create instace for sessionStatusCallback
sessionStatusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connectToFB();
}
});
logout = (Button) findViewById(R.id.logoutButton);
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
...
}
}
});
// publish button
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
}
public void connectToFB() {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
currentSession = new Session.Builder(this).build();
currentSession.addCallback(sessionStatusCallback);
Session.OpenRequest openRequest = new Session.OpenRequest(
MainActivity.this);
openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
openRequest.setPermissions(permissions);
currentSession.openForPublish(openRequest);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (currentSession != null) {
currentSession
.onActivityResult(this, requestCode, resultCode, data);
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (session != currentSession) {
return;
}
if (state.isOpened()) {
// Log in just happened.
Toast.makeText(getApplicationContext(), "session opened",
Toast.LENGTH_SHORT).show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String fbId = user.getId();
String fbName = user.getName();
String gender = user.asMap().get("gender").toString();
String email = user.asMap().get("email").toString();
String first = user.asMap().get("first_name").toString();
String last = user.asMap().get("last_name").toString();
textView.setText("Id: " + fbId + ", Name: " + fbName + ", Gender: " + gender + ", EmailID: " + email + ", First: " + first + ", Last: " + last);
}
});
} else if (state.isClosed()) {
// Log out just happened. Update the UI.
Toast.makeText(getApplicationContext(), "session closed",
Toast.LENGTH_SHORT).show();
}
}
public void publishStory() {
....
}
}
And now I am using same code in one of my project, but always getting:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at c.o.m.MainActivity$5.onCompleted(MainActivity.java:262)
at com.facebook.Request$1.onCompleted(Request.java:303)
at com.facebook.Request$4.run(Request.java:1726)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
At this line, I am getting NPE:
String email = user.asMap().get("email").toString();
Code:
public class MainActivity extends Activity {
Button btnFBLogin, btnGPLogin;
private Session.StatusCallback sessionStatusCallback;
private Session currentSession;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_layout);
sessionStatusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
btnFBLogin = (Button) findViewById(R.id.loginFB);
btnFBLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
connectToFB();
}
});
}
public void connectToFB() {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
currentSession = new Session.Builder(this).build();
currentSession.addCallback(sessionStatusCallback);
Session.OpenRequest openRequest = new Session.OpenRequest(
MainActivity.this);
openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
openRequest.setPermissions(permissions);
currentSession.openForPublish(openRequest);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (currentSession != null) {
currentSession
.onActivityResult(this, requestCode, resultCode, data);
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (session != currentSession) {
return;
}
if (state.isOpened()) {
// Log in just happened.
Toast.makeText(getApplicationContext(), "session opened",
Toast.LENGTH_SHORT).show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String fbId = user.getId();
String fbName = user.getName();
String gender = user.asMap().get("gender").toString();
String email = user.asMap().get("email").toString();
String first = user.asMap().get("first_name").toString();
String last = user.asMap().get("last_name").toString();
Toast.makeText(MainActivity.this, "EmailId:- "+email, Toast.LENGTH_LONG).show();
}
});
} else if (state.isClosed()) {
// Log out just happened. Update the UI.
Toast.makeText(getApplicationContext(), "session closed",
Toast.LENGTH_SHORT).show();
}
}
}
What could be the reason? Why its happening?
Sometime it might be happen that User not set their Email Id in their Profile which are you getting in Your Facebook Login Via Android so that throws Error like Null Pointer Exception.
So You should have to check before using the Email Variable after fetching from Login that it is null or not Such as :
String email ="";
if(user.asMap().get("email") != null){
email = user.asMap().get("email").toString();
}
You need to add "email" to the list of permissions you're requiring, otherwise the email will always be null. I don't know what version of the sdk you're using. With the last one you can write:
Collection<String> mPermissions = new ArrayList<>();
mPermissions.add("email");
LoginManager mLoginManager = LoginManager.getInstance();
CallbackManager mCallbackManager = CallbackManager.Factory.create();
FbCallback fbCallback = new FbCallback(this);
mLoginManager.registerCallback(mCallbackManager, fbCallback);
[...]
mLoginManager.logInWithReadPermissions(this, mPermissions);
By the way...remember that the user can revoke the permission or cannot grant it during the login.
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
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();
}
i'm trying to get the user details on facebook android sdk..
i'm not getting results from Request.newMeRequest(session, new Request.GraphUserCallback() which is an updated function from android sdk manager
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private TextView userInfoTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_location",
"user_birthday", "user_likes"));
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
return view;
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
userInfoTextView.setVisibility(View.VISIBLE);
Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generatedation I put the tags below in wrong
// places (I method stub
if (user != null) {
// Display the parsed user info
Toast.makeText(null, "Entered the user section",
Toast.LENGTH_LONG).show();
userInfoTextView.setText(buildUserInfoDisplay(user));
} else if (user == null) {
Toast.makeText(null, "User is null error in request",
Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
userInfoTextView.setVisibility(View.INVISIBLE);
Log.i(TAG, "Logged out...");
}
}
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();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#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);
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
userInfo.append(String.format("Name: %s\n\n", user.getName()));
userInfo.append(String.format("Birthday: %s\n\n", user.getBirthday()));
userInfo.append(String.format("Location: %s\n\n", user.getLocation()
.getProperty("name")));
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
// JSONArray languages = (JSONArray)user.getProperty("languages");
GraphObjectList<MyGraphLanguage> languages = (user
.cast(MyGraphUser.class)).getLanguages();
if (languages.size() > 0) {
ArrayList<String> languageNames = new ArrayList<String>();
for (MyGraphLanguage language : languages) {
languageNames.add(language.getName());
}
userInfo.append(String.format("Languages: %s\n\n",
languageNames.toString()));
}
return userInfo.toString();
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private interface MyGraphUser extends GraphUser {
// Create a setter to enable easy extraction of the languages field
GraphObjectList<MyGraphLanguage> getLanguages();
}
}
You can try with simple following code.
public class Profile_Detail extends Activity implements OnClickListener {
ImageView profile_pic;
TextView mfirstname, mlastname, mfullname, mfacebookLink, mfacebookId,
mfacebookUnm, mgender, mEmail;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback,
savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
}
}
profile_pic = (ImageView) findViewById(R.id.profile_pic);
mfirstname = (TextView) findViewById(R.id.textView1);
mlastname = (TextView) findViewById(R.id.textView2);
mfullname = (TextView) findViewById(R.id.textView3);
mfacebookLink = (TextView) findViewById(R.id.textView4);
mfacebookId = (TextView) findViewById(R.id.textView5);
mfacebookUnm = (TextView) findViewById(R.id.textView6);
mgender = (TextView) findViewById(R.id.textView7);
mEmail = (TextView) findViewById(R.id.textView8);
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
mfirstname.setText(user.getFirstName());
mlastname.setText(user.getLastName());
mfullname.setText(user.getName());
mfacebookLink.setText(user.getLink());
mfacebookId.setText(user.getId());
mfacebookUnm.setText(user.getUsername()
+ " (" + user.getName() + ")");
String gender = user.asMap()
.get("gender").toString();
String email = user.asMap()
.get("email").toString();
mgender.setText(gender);
mEmail.setText(email);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL image_value = new URL(
"http://graph.facebook.com/"
+ user.getId()
+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory
.decodeStream(image_value
.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state,
Exception exception) {
}
}
}
With this above code i am successfully able to get the detail of facebook user as well as profile picture.