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();
}
}
}
Related
I've been going through docs Android - Facebook login
for days still the issue that I'm facing is - just after the user logs in for first time and after the graph request and the api call,the intentToHomeScreen() method is not called. Note that this happens in rare cases. The progress bar keeps on loading.
Here's my code, sorry for posting such long post:
public class SignInActivity extends BaseActivity {
final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
#BindView(R.id.sign_fb_splash_linear)
LinearLayout mSignIn;
#BindView(R.id.sign_in_logo_img)
ImageView mLogoImg;
#BindView(R.id.splash_relative)
RelativeLayout mRelative;
private CallbackManager mCallbackManager;
private Profile profile;
private String fbid;
private String fUserName;
private String gender;
private String email;
private Uri imageUri;
private SharedPref preferences;
private Context mContext;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
private User userFromResponse;
private GpsLocation mGpsLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting the context
mContext = this;
preferences = SharedPref.getInstance(mContext);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(getApplication());
if (BuildConfig.enableCrashlytics) {
Fabric.with(this, new Crashlytics());
}
setContentView(R.layout.activity_signin);
ButterKnife.bind(this);
mGpsLocation = GpsLocation.getInstance(getApplicationContext(), this);
mGpsLocation.onStart();
if (userIsLoggedIn()) {
intentToHomeScreen();
}
Animation animShow = AnimationUtils.loadAnimation(this, R.anim.slide_up);
mSignIn.startAnimation(animShow);
}
private void intentToHomeScreen() {
Intent intent = new Intent(SignInActivity.this, HomeScreenActivity.class);
startActivity(intent);
finish();
}
private boolean userIsLoggedIn() {
return preferences.getLongValue(mContext, preferences.KEY_USER_ID) != 0;
}
private void initialiseFacebookSdk() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
showProgressBar(true, progressBar);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (Profile.getCurrentProfile() != null && object != null && response != null) {
profile = Profile.getCurrentProfile();
email = object.optString("email");
gender = object.optString("gender");
fbid = profile.getId();
fUserName = profile.getName();
imageUri = profile.getProfilePictureUri(300, 300);
String loginType = "Facebook";
User user = new User();
user.email = email;
user.phoneNumber = "";
user.loginType = loginType;
user.gender = gender;
user.name = fUserName;
user.facebookId = fbid;
// sending to api
IAppAPIInterface apiManagerInterface = ApiManager.getApiManager();
Call<User> call = apiManagerInterface.postFbDetails(user);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
showProgressBar(false, progressBar);
if (response != null && response.body() != null) {
userFromResponse = response.body();
if (preferences != null) {
SharedPref.setBoolean(mContext, preferences.KEY_FIRST_USE_HOME, true);
SharedPref.setLong(mContext, preferences.KEY_USER_ID, userFromResponse.userRecordId);
SharedPref.setString(mContext, preferences.KEY_NAME, userFromResponse.name);
SharedPref.setString(mContext, preferences.KEY_PROF_IMG_URL, String.valueOf(imageUri));
SharedPref.setString(mContext, preferences.KEY_USER_TOKEN, userFromResponse.token);
}
// Sending to home screen
intentToHomeScreen();
} else if (response != null) {
AppUtilityMethods.getInstance(SignInActivity.this).showMsgToast(SignInActivity.this, response.message(), mSignIn);
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
showProgressBar(false, progressBar);
if (t.getMessage().equals("timeout")) {
AppUtilityMethods.getInstance(SignInActivity.this).showMsgToast(SignInActivity.this, getString(R.string.timeout), mSignIn);
} else {
AppUtilityMethods.getInstance(SignInActivity.this).showMsgToast(SignInActivity.this, t.getMessage(), mSignIn);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
showProgressBar(false, progressBar);
Log.d("FACEBOOK", "On Cancel");
}
#Override
public void onError(FacebookException ex)
{
showProgressBar(false, progressBar);
AppUtilityMethods.getInstance(getApplicationContext()).showMsgToast(getApplicationContext(), "Connetion error!", null);
Log.d("FACEBOOK", "On Error: " + ex.getMessage());
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
}
return;
}
case OpenDialogPermission.MY_PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mGpsLocation.isGPSEnable();
} else {
finish();
}
}
}
#Override
protected void onStop() {
super.onStop();
mGpsLocation.onStop();
}
#Override
protected void onStart() {
super.onStart();
mGpsLocation.onStart();
}
#Override
protected void onResume() {
super.onResume();
mGpsLocation.checkPermissions();
}
#OnClick({R.id.sign_fb_splash_linear})
void onClick() {
if (Utilities.isNetworkAvailable(this)) {
mCallbackManager = CallbackManager.Factory.create();
initialiseFacebookSdk();
} else {
AppUtilityMethods.getInstance(this).showNetworkNotAvailToast(this, mSignIn);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
finish();
}
}
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 am using Facebook SDK for my android app.It's log in successfully but after that when i want to access graph api it shows Should not pass a read permission (email) to a request for publish or manage authorization and crashes my apk with null pointer exception.
when i use SessionLoginBehavior.SUPPRESS_SSO it works fine but while using SessionLoginBehavior.SSO_WITH_FALLBACK it show this error
Below is my FacebookService class.
public class FacebookService {
private Context context;
private Session session;
private Session.StatusCallback statusCallback;
private List<String> permissions = Arrays.asList("email", "user_checkins", "user_birthday", "user_hometown",
"user_location");
private FacebookRequestListener facebookRequestListener;
private String profile_url;
public interface FacebookRequestListener {
void signedInFacebookUser(RamblerUser user);
void errorOccuredOnFacebook();
}
public FacebookService(Context context) {
this.context = context;
statusCallback = new SessionStatusCallback();
}
public void login() {
if (session == null) {
session = new Session(context);
Session.setActiveSession(session);
}
setupRequest();
}
public void logOut() {
session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
public Boolean isSessionAvailable() {
if (session == null)
return false;
else
return session.isOpened();
}
private void setupRequest() {
OpenRequest request = new Session.OpenRequest(((Activity) context));
request.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
request.setCallback(statusCallback);
request.setPermissions(permissions);
session.openForPublish(request);
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
callProfilePictureApi();
}
}
}
public void addCallback() {
if (session != null) {
if (statusCallback != null)
Session.getActiveSession().addCallback(statusCallback);
}
}
public void removeCallback() {
if (session != null) {
if (statusCallback != null)
Session.getActiveSession().removeCallback(statusCallback);
}
}
public void activityResult(int requestCode, int resultCode, Intent data) {
Session.getActiveSession().onActivityResult(((Activity) context), requestCode, resultCode, data);
}
public void setFacebookRequestListener(FacebookRequestListener facebookRequestListener) {
this.facebookRequestListener = facebookRequestListener;
}
private void callProfilePictureApi() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("height", "200");
params.putString("type", "normal");
params.putString("width", "200");
/* make the API call */
new Request(session, "/me/picture", params, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
GraphObject go = response.getGraphObject();
// go.getProperty("url");
JSONObject obj = go.getInnerJSONObject();
try {
profile_url = obj.getJSONObject("data").get("url").toString();
callProfileApi();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
facebookRequestListener.errorOccuredOnFacebook();
}
}
}).executeAsync();
}
private void callProfileApi() {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if (user != null) {
String email = user.asMap().get("email").toString();
// Log.i("profile url", ""+
RamblerUser rambleUser = new RamblerUser();
rambleUser.socialId = user.getId();
rambleUser.address = user.getLocation() != null ? user.getLocation().getName() : "NA";
rambleUser.email = user.asMap().get("email").toString();
rambleUser.socialType = com.rambler.Rambler.LoginType.GPlus;
rambleUser.gender = "NA";
rambleUser.socilaProfileImageUrl = "NA";
rambleUser.socilaProfileImageUrl = profile_url;
rambleUser.name = user.getName();
rambleUser.screenName = user.getUsername();
Log.i("email address", email);
facebookRequestListener.signedInFacebookUser(rambleUser);
} else {
facebookRequestListener.errorOccuredOnFacebook();
}
}
}).executeAsync();
}
}
Use ReadPermissions instead of PublishPermissions. You are trying to request read permissions with a function that is being used for publish permissions.
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.