Facebook wall post error from Android app? - android

I have successfully integrated FB with my app.I want to auto post some text,links,images to my facebook wall after giving app permission from facebook account.I have tried using below provided logic but am getting
{Response: responseCode: 403,graphObject: null,error: {errorCode: 200,errorType:
OAuthException,errorMessege: (#200) The user hasn't authorized the application
to perform this action}, isFromCache:false
FacebookActivity.java
public class FacebookActivity extends FragmentActivity {
private MainFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
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 void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Bundle params = new Bundle();
params.putString("message", "Hey I am using this app");
params.putString("name", "Dexter");
params.putString("caption", "londatiga.net");
params.putString("link", "http://www.londatiga.net");
params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");
String uri = "/me/feed?message=" + "Hey I am using this app" + "" + "&access_token=" + session.getAccessToken();
uri = uri.replace(" ", "%20");
new Request(
session,
uri,
params,
HttpMethod.POST,
new Request.Callback() {
public void onCompleted(Response response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
}
}
).executeAsync();
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_facebook, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
if(Session.getActiveSession().isOpened()){
Toast.makeText(getActivity(), "logged in to FB", 1).show();
authButton.setReadPermissions(Arrays.asList("email", "read_stream"));
authButton.clearPermissions();
authButton.setPublishPermissions(Arrays.asList("publish_actions"));
}else{
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("public_profile"));
}
return view;
}
#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);
}
}

The error message means that you did not authorize the user with publish_actions. Test the Access Token in the Debugger to find out which permissions are authorized: https://developers.facebook.com/tools/debug/
Btw, you will not get read_stream approved in the review process: https://developers.facebook.com/docs/facebook-login/permissions/v2.3#reference-read_stream
...meaning, it will only work for Users with a role in the App (Admin, Developer, Tester).

finally after lots of research i have modified my class correctly.Here i am posting my modified code that may help others.
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
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 void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
publishStory(session);
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
public void publishStory(Session currentSession) {
Bundle params = new Bundle();
params.putString("message", "Hey I am using this app");
params.putString("name", "Dexter");
params.putString("caption", "londatiga.net");
params.putString("link", "http://www.londatiga.net");
params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(),currentSession, params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Intent i=new Intent(getActivity(),MainActivity.class);//FacebookActivity.class);
startActivity(i);
getActivity().finish(); // do some stuff
} else {
// User clicked the Cancel button
Toast.makeText(getActivity(),
"Publish cancelled", Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity(),
"Publish cancelled", Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity(),
"Error posting story", Toast.LENGTH_SHORT).show();
}
}
}).setFrom("").build();
feedDialog.show();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_facebook, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
if(Session.getActiveSession().isOpened()){
Toast.makeText(getActivity(), "logged in to FB", 1).show();
}else{
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("public_profile"));
}
return view;
}
#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);
}
}

Related

Facebook Login Button with email responce

I had implemented the facebook button following the facebook guide.It's working perfectly but
first_name,
last_name,
email,
sex,
fb_id.
I got all the things except email.Might be I need to give some permission But I can't find it where to give it.
MainActivity.class
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
private LoginButton loginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback()
{
#Override
public void onUserInfoFetched(GraphUser user)
{
if (user != null)
{
Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
i.putExtra("first_name", user.getFirstName());
i.putExtra("last_name", user.getLastName());
//i.putExtra("email", user.asMap().get("email").toString());
i.putExtra("sex", user.asMap().get("gender").toString());
i.putExtra("fb_id", user.getId());
Log.i("first_name", user.getFirstName());
Log.i("last_name", user.getLastName());
//Log.i("email", user.getProperty("email").toString());
Log.i("sex", user.asMap().get("gender").toString());
Log.i("fb_id", user.getId());
finish();
startActivity(i);
}
else
{
Log.i("TAG", "You are not logged");
}
}
});
if (savedInstanceState == null)
{
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
}
else
{
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
public void goingToRegister(View v)
{
v.findViewById(R.id.buttonRegister).startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.image_click));
Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
finish();
startActivity(i);
}
public void loginNow(View v)
{
v.findViewById(R.id.buttonLogin).startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.image_click));
Intent i = new Intent(MainActivity.this, LoginActivity.class);
finish();
startActivity(i);
}
}
MainFragment.class
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.main_activity, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.fb_login_button);
authButton.setReadPermissions(Arrays.asList("public_profile","email","user_friends"));
authButton.setFragment(this);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception)
{
if (state.isOpened())
{
Log.i(TAG, "Logged in...");
}
else if (state.isClosed())
{
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();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
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);
Log.i("TAG", "responce: " + 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);
}
}
In facebook I added the permission like this
The email field is not a standard one that is returned from the me endpoint, so you will need a specific Request to fetch it using the Request class.
Use this https://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/Request.java#L278
Set the fields on it that you want, like:
// Make sure the user is logged in first
Request meRequest = Request.newMeRequest(Session.getActiveSession(), yourCallback);
Bundle parameters = new Bundle();
// The fields you want in comma separated list
parameters.putString(fields, "id,name,email");
meRequest.setParameters(parameters);
meRequest.executeAsync();
You need the email permission before that works though.
You can use the graph api explorer to see for the graph request should behave.
Try this library, this is the simplest way to handle facebook https://github.com/sromku/android-simple-facebook

Nothing happens after Facebook login requests is authenticated

I am trying to login Android app through Facebook.
After clicking the Facebook login button, a new web view opens where it asks for permission, I press OK and then it got close and application is already closed, hence nothing.
public class Splash extends FragmentActivity {
private MainFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction() .add(android.R.id.content,mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
}
public class MainFragment extends Fragment {
private static final String TAG = "FBLoginFragment";
private UiLifecycleHelper mUiHelper;
private OnFBAccessTokenPass mTokenPasser;
private String mSessionToken;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
mSessionToken = session.getAccessToken();
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// pass the access token to the activity
// with the user id
mTokenPasser.onFBAccessTokenPass(mSessionToken, user.getId());
}
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
mSessionToken = "";
}
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
//mTokenPasser = (OnFBAccessTokenPass) a;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUiHelper = new UiLifecycleHelper(getActivity(), callback);
mUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
mUiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
mUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mUiHelper.onSaveInstanceState(outState);
}
public interface OnFBAccessTokenPass {
public void onFBAccessTokenPass(String accessToken, String uid);
}
}
In Manifest
<activity
android:name="com.facebook.LoginActivity"
android:theme="#style/AppTheme" >
</activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
I think the problem is that main activity gets the result. So override the main's activity onActivityResult to allow the fragment to get the result add this to your main activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
and change the position of authButton.setFragment(this); just before the return view;

How to publish photo to facebook without aproval

I want to publish my bitmap photo to my app's album without approving it from facebook. As far as I did it has a loginButton when a login is successfull a share button appears and the bitmap photo is uploaded when he share button is clicked. Everything is going fine but I had to approve the photo from the album to share it with my friends. here is my code which is described by developers site of facebook with fragment
public class MainFragment extends Fragment implements OnClickListener {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
LoginButton authButton;
Button bShare;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
bShare = (Button) view.findViewById(R.id.bShare);
bShare.setOnClickListener(this);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#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 void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
bShare.setVisibility(View.VISIBLE);
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
bShare.setVisibility(View.INVISIBLE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data,
new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.e("Activity",
String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(
FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
#Override
public void onClick(View v) {
Bitmap image = Joursey.img;
Request.Callback UploadCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() != null) {
Log.d("Upload",
"photo upload problem. Error="
+ response.getError());
Toast.makeText(getActivity(),
"Problem occured while uploading",
Toast.LENGTH_LONG).show();
}
Object graphResponse = response.getGraphObject().getProperty(
"id");
if (graphResponse == null || !(graphResponse instanceof String)
|| TextUtils.isEmpty((String) graphResponse)) {
Log.d("Upload", "failed photo upload/no response");
Toast.makeText(getActivity(),
"Failed to upload/no response", Toast.LENGTH_LONG)
.show();
} else {
Log.d("Upload", "Successfully Uploaded");
Toast.makeText(getActivity(), "Successfully Uploaded",
Toast.LENGTH_LONG).show();
}
}
};
Request request = Request.newUploadPhotoRequest(
Session.getActiveSession(), image, UploadCallback);
Bundle params = request.getParameters();
params.putString("name", "This is my favorite jursey");
request.setParameters(params);
request.executeAsync();
}
}
I want such that I dont need to aprove it from my profile, it should be auto published? what change d I need to make here?

NewPermissionsRequest Callback is not called

This is my code:
public class MainFragment extends Fragment implements OnClickListener {
private static final String EMAIL_PERMISSION = "email";
private static final String TAG = MainFragment.class.getSimpleName();
private UiLifecycleHelper uiHelper;
private LoginButton loginButton;
private GraphUser loggedInUser;
private TextView tvUserName, tvEmail;
private Button btnRequestEmail;
private Session mSession;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
tvUserName = (TextView) view.findViewById(R.id.tv_username);
tvEmail = (TextView) view.findViewById(R.id.tv_email);
btnRequestEmail = (Button) view.findViewById(R.id.btn_requestEmail);
btnRequestEmail.setOnClickListener(this);
loginButton = (LoginButton) view.findViewById(R.id.btn_login);
loginButton.setReadPermissions(Arrays.asList("public_profile"));
loginButton.setFragment(this);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
loggedInUser = user;
updateUI();
}
});
return view;
}
#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 void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
mSession = session;
btnRequestEmail.setEnabled(true);
makeMeRequest(session);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_requestEmail:
requestEmailPermissions();
break;
default:
break;
}
}
private void requestEmailPermissions() {
Session.NewPermissionsRequest newPermissionsRequest =
new Session.NewPermissionsRequest(getActivity(), Arrays.asList(EMAIL_PERMISSION));
newPermissionsRequest.setCallback(new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if(session.isPermissionGranted(EMAIL_PERMISSION)){
Toast.makeText(getActivity(), "Email permission granted :)", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "Email permission denied :(", Toast.LENGTH_LONG).show();
}
}
});
Session.getActiveSession().requestNewReadPermissions(newPermissionsRequest);
}
private void makeMeRequest(final Session session) {
Request request = Request.newMeRequest(session,
new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (session == Session.getActiveSession()) {
loggedInUser = user;
updateUI();
}
if (response.getError() != null) {
Log.e(TAG, response.getError().getErrorMessage());
}
}
});
request.executeAsync();
}
protected void updateUI() {
if (loggedInUser != null) {
tvUserName.setText(getString(R.string.welcome_user,
loggedInUser.getFirstName()));
if (loggedInUser.asMap().get(EMAIL_PERMISSION) != null) {
String email = loggedInUser.asMap().get(EMAIL_PERMISSION).toString();
tvEmail.setText(email);
}
} else {
tvUserName.setText("");
}
}
}
At first I login with the default facebook login button.
When the session is opened I enable the 'request email permission' button.
I request the email permission when the user clicks that button.
This works and I see the permission request screen, but I want to capture if the user doesn't accept the permission.
So I've added this callback to check if the permission is granted:
newPermissionsRequest.setCallback(new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if(session.isPermissionGranted(EMAIL_PERMISSION)){
Toast.makeText(getActivity(), "Email permission granted :)", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "Email permission denied :(", Toast.LENGTH_LONG).show();
}
}
});
But this callback is never called. How can I fix this?
PS: I'm using version 3.14.1 of the Facebook SDK
The correct activity's onActivityResult method must be called for your newPermissionRequest callback to run.
If the newPermissionRequest is happening in a fragment, make sure the activity's onActivityRequest call is passed to it by overriding onActivityRequest in your activity and then explicitly calling onActivityRequest in your fragment, something like this:
MyActivity.java:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getSupportFragmentManager().findFragmentById(R.id.my_fragment_frame).onActivityResult(requestCode, resultCode, data);
}
onActivityResult can fail to be called if you have a mixture of static (xml) and dynamic (programmatic) fragments. For more information, please see this the accepted answer here: FB sdk, requestNewPublishPermissions() doesn't call any callback
In my case, my newPermissionRequest was attached to a different activity than I thought, so I was seeing onActivityResult getting called, but I didn't realize that it was the wrong activity.

After facebook login, how go to another activity from viewpager ?

I have a facebook login button on a viewpager with circlepageindicator.
When i click on that, it authenticates the user and changes login button to logout there itself.
What i want is that, (1). user should be directed to a new activity ( which is my navigation drawer activity) with the session. (2). how do i pass/authenticate sessions between each activity and for each api requests ?
Here is my MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter adapter=new MyPagerAdapter();
pager = (ViewPager)findViewById(R.id.view_pager);
pager.setAdapter(adapter);
pager.setCurrentItem(0);
//Bind the title indicator to the adapter
CirclePageIndicator titleIndicator = (CirclePageIndicator)findViewById(R.id.titles);
titleIndicator.setViewPager(pager);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
#Override
public void onBackPressed() {
if (pager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
pager.setCurrentItem(pager.getCurrentItem() - 1);
}
}
}
Here is my MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
return view;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// Request user data and show the results
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.i(TAG, user.getName()+" ***** "+user.getBirthday());
Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
#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);
}
}
Referred many examples but couldn't succeed. Stuck with this from many days.
Any suggestions accepted. Thank you.
When Call Back comes from facebook
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
....
When user != null you should get user data and then start the new activity
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
intent.putExtra("Fb_id", user.getId());
intent.putExtra("user_name", user.getName());
startActivity(intent);
Every time you want to get the facebook open session
Session currentSession = Session.getActiveSession();
In the onSessionStateChange method, do what you want after a successful login, in the below sample I am redirecting the page to main dashboard.
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
if (state.isOpened()) {
//Succussful Loggin
Intent intent = new Intent(getActivity(), Dashboard.class);
startActivity(intent);
} else if (state.isClosed()) {
//Loggedout
}
}

Categories

Resources