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.
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 am using Facebook SDK 3.2 for login in my android app.
Login, logout functions working fine.
My Problem:
after login want to retrieve the Facebook Username and Email.
Username Showing Perfectly Email is not Showing.
Please help me to solve it.
MainActivity.java
public class MainActivity extends FragmentActivity {
String TAG="MainActivity";
private static final String PERMISSION = "publish_actions";
//private static final String PERMISSION = "email";
private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";
private Button postStatusUpdateButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
Button LogoutButton,Pro;
/* private static final List<String> PERMISSION = Arrays.asList(
"email","publish_actions");*/
private enum PendingAction
{
NONE, POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.d(TAG, String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
Log.d(TAG, "Success!");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
// Can we present the share dialog for regular links?
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.activity_main);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback()
{
#Override
public void onUserInfoFetched(GraphUser user)
{
MainActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to
// be populated in order to post a status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
}
});
LogoutButton=(Button)findViewById(R.id.LogoutButton);
LogoutButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//callFacebookLogout(session);
Logout();
}
});
}
//override lifecycle methods so that UiLifecycleHelper know about state of the activity
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,Exception exception)
{
if (state.isOpened()) {
Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();
getUserData(session,state);
} else if (state.isClosed()) {
Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
}
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException
|| exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(MainActivity.this)//if permission is not granted
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI()
{
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons
|| canPresentShareDialog);
if (enableButtons && user != null)
{
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result,
FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post,
message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
.setPositiveButton(R.string.ok, null).show();
}
// create sample post to update on facebook
private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("Hello Facebook")
.setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
.setLink("http://androidsrc.net/");
}
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update,
user.getFirstName(), (new Date().toString()));
Request request = Request.newStatusUpdateRequest(
Session.getActiveSession(), message, place, tags,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message,
response.getGraphObject(),
response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
//check if app has permission to publish on facebook
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when
// we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
public void Logout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
}
Session.setActiveSession(null);
}
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)
{
try
{
String name = user.getName();
// If you asked for email permission
String email = (String) user.getProperty("email");
// Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
//Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
method for getting the User data from Facebook, after Logged in
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)
{
try
{
String name = user.getName();
// If you asked for email permission
String email = (String) user.getProperty("email");
// Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
//Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
I found the Solution for my Question
I have Missed the Permission for getting the facebook Profile email in My code
added the permission below my login button inside oncreate method
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email","user_photos"));
Now its working fine
I am using Facebook login in android app,Its Login Successfully .
after Successful login intent goes to next page.
from Second page i am trying to logout the Facebook ,its not Working
Help me to resolve it.
else suggest me Working example for Facebook Login,logout,Getting profile information Latest SDK4.2.
Link I have used
My Logout method
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state)
{
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true)
{
//Logout Successss
}
}
});
}
This My Facebook Login Code
AndroidFacebookConnectActivity.java
public class AndroidFacebookConnectActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "*************" ; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;
Button Logout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
Logout=(Button)findViewById(R.id.btn_show_Logout);
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAccessTokens();
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Logout Button CLicked", "button Clicked");
logoutFromFacebook();
}
});
}
/**
* Function to login into facebook
* */
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
Logout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
Logout.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
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() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
Logout.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I found the Solution for my Question
i replaced my Facebook SDK 3.0 to 3.2 .
also changed the code for facebook login.
now Logout and Login Working fine.
MainActivity.java
public class MainActivity extends FragmentActivity {
String TAG="MainActivity";
private static final String PERMISSION = "publish_actions";
//private static final String PERMISSION = "email";
private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";
private Button postStatusUpdateButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
Button LogoutButton,Pro;
/* private static final List<String> PERMISSION = Arrays.asList(
"email","publish_actions");*/
private enum PendingAction
{
NONE, POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception)
{
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.d(TAG, String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
Log.d(TAG, "Success!");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
// Can we present the share dialog for regular links?
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.activity_main);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback()
{
#Override
public void onUserInfoFetched(GraphUser user)
{
MainActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to
// be populated in order to post a status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
}
});
LogoutButton=(Button)findViewById(R.id.LogoutButton);
LogoutButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//callFacebookLogout(session);
Logout();
}
});
}
//override lifecycle methods so that UiLifecycleHelper know about state of the activity
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,Exception exception)
{
if (state.isOpened()) {
Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();
getUserData(session,state);
} else if (state.isClosed()) {
Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
}
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException
|| exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(MainActivity.this)//if permission is not granted
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI()
{
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons
|| canPresentShareDialog);
if (enableButtons && user != null)
{
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result,
FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post,
message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
.setPositiveButton(R.string.ok, null).show();
}
// create sample post to update on facebook
private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("Hello Facebook")
.setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
.setLink("http://androidsrc.net/");
}
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update,
user.getFirstName(), (new Date().toString()));
Request request = Request.newStatusUpdateRequest(
Session.getActiveSession(), message, place, tags,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message,
response.getGraphObject(),
response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
//check if app has permission to publish on facebook
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when
// we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
public void Logout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
}
Session.setActiveSession(null);
}
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)
{
try
{
String name = user.getName();
// If you asked for email permission
String email = (String) user.getProperty("email");
// Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
//Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
My logout Method
public void Logout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
}
Session.setActiveSession(null);
}
Link i reffered
link
If you are using latest facebook sdk 4.0 then
LoginManager.getInstance().logOut();
Will work.
dependencies {
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
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.
I am creating an app that take some text input from user and post it into the usr's wall
I am using following code for posting text
private void post_to_wall(String user_text) {
// TODO Auto-generated method stub
Log.d("post to wall", user_text);
try{
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", user_text);
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
}catch(Exception e) {
e.printStackTrace();
}
}
after running this code nothing happens.No error is occuring.
Plz tell me how to check whether a user is logged in or not..Bascially what i want to do if user is logged in fb app then allow him topost text otherwise tell him to login first.
Thnx
Look at the publishStory method of sample.
https://developers.facebook.com/docs/android/publish-to-feed/
They use a HTTPPost and RequestAsyncTask. Call back which parses the response and a id is displayed as a toast to confirm success of posting
Example:
private void publishStory(String user_text) {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("message", user_text);
postParams.parameters.putString("description", "test test test");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
Edit:
Check the facebook login sample
https://developers.facebook.com/docs/android/login-with-facebook/
The prerequisite for publish sample is to login into facebook.
try this :
public class HelloFacebookSampleActivity extends FragmentActivity {
private static final String PERMISSION = "publish_actions";
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private Button postStatusUpdateButton;
private Button postPhotoButton;
private Button pickFriendsButton;
private Button pickPlaceButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
private enum PendingAction {
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
Log.d("HelloFacebook", "Success!");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState
.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.main);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton
.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
HelloFacebookSampleActivity.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to
// be populated in order to post a
// status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});
postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});
pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
});
pickPlaceButton = (Button) findViewById(R.id.pickPlaceButton);
pickPlaceButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickPlace();
}
});
controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);
final FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment != null) {
// If we're being re-created and have a fragment, we need to a) hide
// the main UI controls and
// b) hook up its listeners again.
controlsContainer.setVisibility(View.GONE);
if (fragment instanceof FriendPickerFragment) {
setFriendPickerListeners((FriendPickerFragment) fragment);
} else if (fragment instanceof PlacePickerFragment) {
setPlacePickerListeners((PlacePickerFragment) fragment);
}
}
// Listen for changes in the back stack so we know if a fragment got
// popped off because the user
// clicked the back button.
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (fm.getBackStackEntryCount() == 0) {
// We need to re-show our UI.
controlsContainer.setVisibility(View.VISIBLE);
}
}
});
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
// Call the 'activateApp' method to log an app event for use in
// analytics and advertising reporting. Do so in
// the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(this);
updateUI();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(HelloFacebookSampleActivity.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons
|| canPresentShareDialog);
postPhotoButton.setEnabled(enableButtons);
pickFriendsButton.setEnabled(enableButtons);
pickPlaceButton.setEnabled(enableButtons);
if (enableButtons && user != null) {
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but
// we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result,
FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post,
message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
.setPositiveButton(R.string.ok, null).show();
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("Hello Facebook")
.setDescription(
"The 'Hello Facebook' sample application showcases simple Facebook integration")
.setLink("http://developers.facebook.com/android");
}
private void postStatusUpdate() {
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilder().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else if (user != null && hasPublishPermission()) {
final String message = getString(R.string.status_update,
user.getFirstName(), (new Date().toString()));
Request request = Request.newStatusUpdateRequest(
Session.getActiveSession(), message, place, tags,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message,
response.getGraphObject(),
response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, false);
}
private void postPhoto() {
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeResource(this.getResources(),
R.drawable.icon);
Request request = Request.newUploadPhotoRequest(
Session.getActiveSession(), image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post),
response.getGraphObject(),
response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
private void showPickerFragment(PickerFragment<?> fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception, error.getMessage());
Toast toast = Toast.makeText(HelloFacebookSampleActivity.this,
text, Toast.LENGTH_SHORT);
toast.show();
}
});
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.fragment_container, fragment)
.addToBackStack(null).commit();
controlsContainer.setVisibility(View.GONE);
// We want the fragment fully created so we can use it immediately.
fm.executePendingTransactions();
fragment.loadData(false);
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void setFriendPickerListeners(final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
showAlert(getString(R.string.you_picked), results);
}
private void onPlacePickerDone(PlacePickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String result = "";
GraphPlace selection = fragment.getSelection();
if (selection != null) {
result = selection.getName();
} else {
result = getString(R.string.no_place_selected);
}
place = selection;
showAlert(getString(R.string.you_picked), result);
}
private void onClickPickPlace() {
final PlacePickerFragment fragment = new PlacePickerFragment();
fragment.setLocation(SEATTLE_LOCATION);
fragment.setTitleText(getString(R.string.pick_seattle_place));
setPlacePickerListeners(fragment);
showPickerFragment(fragment);
}
private void setPlacePickerListeners(final PlacePickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new PlacePickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
onPlacePickerDone(fragment);
}
});
fragment.setOnSelectionChangedListener(new PlacePickerFragment.OnSelectionChangedListener() {
#Override
public void onSelectionChanged(PickerFragment<?> pickerFragment) {
if (fragment.getSelection() != null) {
onPlacePickerDone(fragment);
}
}
});
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(this).setTitle(title).setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null
&& session.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when
// we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
}