How to log in to facebook on android - android

I have tried the tutorial http://developers.facebook.com/docs/mobile/android/build/#sdk and I am able to login successfully. this code provides a dialog to login. But I want to make this as an Activity . Because I have to perform other tasks too from this activity. Like when new activity starts after sucessful login come back to previous (facebook) activity again in previous state of facebook. Please help me.
Thanks

The dialog is only created for the user to log into Facebook. Once they have done that it will return back to the original activity. This is what you are asking for right?
Lets say you want to post a message to facebook.
try {
Log.d(TAG, "postToFaceBook()");
if (facebook == null) {
facebook = new Facebook(API);
String access_token = prefs.getFBAccesTocken();
long expires = prefs.getFBExpiry();
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
}
if (facebook.isSessionValid()) {
Log.d(TAG, "Session is valid");
facebook.extendAccessTokenIfNeeded(this, null);
postToFacebook();
} else {
Log.d(TAG, "not valid");
// Using SSO OAuth
// facebook.authorize(this, new String[] { "publish_stream"
// },new LoginDialogListener());
// Not using SSO
facebook.authorize(this, new String[] { "publish_stream" },
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
} catch (NullPointerException e) {
Log.e(TAG, "An error occurd trying to open facebook app");
If the user has logged onto facebook in the past and has a valid session, it will simply post to Facebook if there is not a valid session it will open up the dialog and try to log in.
The LoginDialogListener() responds to the response of this.
public class LoginDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
Log.d(TAG, "Login response recieved");
prefs.saveToken(facebook.getAccessToken());
prefs.saveExpiry(facebook.getAccessExpires());
facebook.extendAccessTokenIfNeeded(MyActivity.this, null);
Log.d(TAG, "Logged in ");
postToFacebook();
}
}
The other option is to look at using SSO (which I have commented out in the example code).

Related

Android: Sign in with Twitter/ Share via Twitter native App navigates to Twitter home screen instead of login screen[inconsistent]

We have an application which supports normal login using a valid email id as well as using Twitter. We are supporting post tweets using our application.
Before posting tweet I m checking for Twitter session. If there is no active session, I m navigating user to Twitter login screen by calling TwitterAuthClient.authorize() method. After authorizing the user able to see the Tweet composer box where user can compose and post tweet. The flow is working properly most of the times. But sometimes the Twitter SDK is opening the Twitter home screen https://drive.google.com/file/d/0Bz670htOa0h6X1NPajNLSS1YVzNvN2F1VWh2WEhzR0N0YTc0/view?usp=sharing
instead of https://drive.google.com/file/d/0Bz670htOa0h6U0xLT0hxcUUyYVUtVXVfV1RTSTNEWFo3LThF/view?usp=sharing screen.
Due to this the callback is not coming back to my application after sign in. So, I m not able to Tweet.
NOTE: Twitter app is installed in my device and there is not active Twitter session present.
Code:
private void postViaTwitter() {
if (Twitter.getSessionManager().getActiveSession() != null ||
!(Utils.isAppPresent(AppConstant.TWITTER_PACKAGE_NAME, this))) {
URL url = null;
try {
url = new URL(UrlUtils.APP_URL);
TweetComposer.Builder tweetComposer = new TweetComposer.Builder(this)
.text(getString(R.string.share_content_description))
.url(url);
tweetComposer.show();
} catch (MalformedURLException e) {
Log.e("Exception", e.getMessage(), e);
}
} else {
loginAndShareUsingTwitter();
}
}
private void loginAndShareUsingTwitter() {
TwitterAuthClient client = new TwitterAuthClient();
client.authorize(this, new com.twitter.sdk.android.core.Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
if (result != null) {
TwitterSession session = result.data;
if (session != null) {
postViaTwitter();
}
}
}
#Override
public void failure(TwitterException exception) {
}
});
}

Android - Facebook session CLOSED when using ParseFacebookUtils.logIn

I am using Facebook and Parse SDK in my Android app. I followed this tutorial for Facebook login and authentication, changing between fragments for login fragment and main menu fragment depending on whether the session state is OPENED in the Session.StatusCallback. And the app works perfectly before integrating with Parse.
And now I encounter a problem. In the onResume() method of the main menu fragment, I added the following code.
final Session session = Session.getActiveSession();
if(session != null && session.isOpened()) {
Request meRequest = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser graphUser, Response response) {
if(session == Session.getActiveSession()) {
// Check if the session is same as usual
ParseFacebookUtils.logIn(graphUser.getId(), session.getAccessToken(),
session.getExpirationDate(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
// The user wasn't saved.
System.out.println("User was not saved to Parse. ");
} else {
// The user has been saved to Parse.
System.out.println("User has successfully been saved to Parse.");
if (user.isNew()) {
// This user was created during this session with Facebook Login.
System.out.println("ParseUser created.");
} else {
// This user existed before.
System.out.println("User exists in Parse. Pull their values: " + user);
}
}
}
});
}
}
});
meRequest.executeAsync();
}
So when the fragment is resumed and the Facebook session is opened, the Facebook user is added to the Parse database so that I can use ParseUser to put and get data afterwards. But the problem happens when using ParseFacebookUtils.logIn(), that it makes the Facebook session CLOSED and invokes the Session.StatusCallback, thus switching the visible fragment back to the login fragment.
I was dealing with this problem all day but cannot find a solution. I have added the code below in an Application but still not work.
Parse.enableLocalDatastore(this);
Parse.initialize(this, Application_id, Client_key);
ParseFacebookUtils.initialize(getString(R.string.facebook_app_id));
Is there a way to fix this? I have read this but no quite good solution is provided. Thanks in advance!
I was trying to do the same thing today. I was using the facebook sdk's UiLifecycleHelper to do the facebook login, make the graph api request and add the user to Parse db. That is how it is done in the example you mentioned - which I think is a bit outdated.
ParseFacebookUtils handles the session and all we need to do is call the login method on it, make the graph api call, get user data like email and update the user field.
Here's some code:
private void parseFacebookLogin(){
ParseFacebookUtils.logIn(this, PARSE_FB_LOGIN_CODE, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d(tag, "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(tag, "User signed up and logged in through Facebook!");
Request.newMeRequest(ParseFacebookUtils.getSession(), graphUserCallback).executeAsync();
} else {
Log.d(tag, "User logged in through Facebook!");
}
}
});
}
GraphUserCallback graphUserCallback = new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null){
getUserDataFacebook(user);
Log.d(tag, response.toString());
}
}
};
private void getUserDataFacebook(GraphUser user){
//get user data here
}
Check out Parse's docs on Facebook login.
Let me know if this works for you.

facebook request dialog android shows only a partial list of friends

Im trying to use facebook request dialog to enable the user to pick a friend to challenge in a turn based trivia android game.
i dont have a web version of the game so i dont canvas.
ive set up a request dialog that shows the list friends which works fine when i log in with facebook test users but when i login with my user who is also administrator of the facebook app then the dialog shows a list of only 5 friends. the dialog allows to search for more friends and when i do that i can search for other friends which do not appear in the list.
my user has "public_profile","read_friendlists", "user_friends" permissions.
the request dialog code
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message", "Learn how to make your Android apps social");
params.putString("filters", "app_non_users");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(MainActivity.this,
//getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
Toast.makeText(getApplicationContext(),
//getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
//getActivity().getApplicationContext(),
"Network Error",
Toast.LENGTH_SHORT).show();
}
} else {
final String requestId = values.getString("request");
if (requestId != null) {
Toast.makeText(getApplicationContext(),
//getActivity().getApplicationContext(),
"Request sent",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
//getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
})
.build();
requestsDialog.show();
}
i dont understand why its not showing the entire friends list. please help.
in addition, is this method of challenging a friend for a game is permitted by facebook is there another more recommended method?
Thanks!
user_friends will return only the friends who used the app that makes the request. via Graph API Reference

WebDialog share post on Facebook when user removes app from settings

Hi I have problem with Facebook:
Case:
1.User has no Facebook app.
2.User logins into Facebook via WebDialog
3.User gives all permissions for share, and shares post
4.User enters Facebook account, than into applications, and removes my app.
5.User tries to make share again.
6."Unknown error. Please try again later" Appears in WebDialog.
Is there a way to fix this case?
I found that using ShareDialog i can avoid this problem when user has facebook app installed, but I don't know how to solve it if user has no fb app on his phone.
To show dialog I verify:
private boolean checkFacebookLogin(){
Session session = Session.getActiveSession();
if(session!=null && session.isOpened() ){
return true;
}
return false;
}
Than i ask for permissions if they are needed:
private void performPublish() {
Session session = Session.getActiveSession();
pendingAction = PendingAction.POST_STATUS_UPDATE;
if (session != null && mCurrentActivity!=null) {
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
} else {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(mCurrentActivity, PERMISSIONS));
}
}
}
In the end i show WebDialog:
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(mCurrentActivity,
Session.getActiveSession(),
postParams))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
}
})
.build();
feedDialog.show();
After showing WebDialog, it redirects to error page with "Unknow error [...]" text, i have found no error information, so I don't even know that something goes wrong.
I tried HelloFacebookSample, but there if user has no facebook app, he can't edit post in facebook dialog. I want to see Facebook dialog in both cases ( with/without fb app installed).
if (FacebookDialog.canPresentShareDialog(this,
FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
this)
.setLink(// what ever you want to share use here
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Log.d("Tag", "Success!");
publishFeedDialog();
} else {
//ask the user to login .
//authButton.performClick();
share = true;
// }
}
So from the above code if the fb app is already installed it will open that app else you have to ask the user to login by performing Fb LoginButton . performClick(). so the user will be redirected to web dialog of fb login. the onLogin success call back u can share using.,
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("link",
"");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
MenuActivity.this, Session.getActiveSession(), 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) {
Toast.makeText(MenuActivity.this, "Posted",
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(
MenuActivity.this
.getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(
MenuActivity.this.getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
} else {
// Generic, ex: network error
Toast.makeText(
MenuActivity.this.getApplicationContext(),
"Error posting story", Toast.LENGTH_SHORT)
.show();
}
}
}).build();
feedDialog.show();
}

Sharing a wall post by facebook android sdk

Hi I am new to android programming. I want to share a image with some description on facebook.
I have tried every method explain in answers on stackoverflow. My problem is facebook dialog opens but it doesn't have specified bundle parameters.
Please help me with this. I have already tried almost 20 different code snippets. Please give me fully functional code.
#Override
public void onClick(View v) {
fb = new Facebook(app_id);
Bundle par = new Bundle();
par.putString("name", "Ass");
fb.dialog(con,"feed",par, new DialogListener(){
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError arg0) {
// TODO Auto-generated method stub
}});
}
});
}
Have you already set up the facebook side of the application on the development page?
You need to have your app registered on facebook if you are intending to use their api and/or do graph requests or wall posts on behalf of a user authtoken.
You should read this tutorial (check part 5 for fb app registering) and all of the related info around it to really get going with facebook interaction within your app.
I know I did and end up creating my own library for log-in short-cuts or graph requests etc... it's not that simple, it will take you some time aswell.
Also;
Are you using the loginButton from the sdk? Like this:
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
It automatically handles user login to facebook whether he has the facebook app installed or not and retrieves a session status result (onStatusChange callback).
Make sure you handle that right first and that the session is correctly initiated.
Still, posting your log will give us a better idea of what you encountering with.
I have to say, tho, that the facebook api for android is pretty solid so far so you must be doing something wrong for sure.
<<<<<< EDIT: >>>>>>
Ok then, assuming you have the user correctly logged-in (session.getActiveSession() == Session.OPENED I believe), the next step is to make sure you enabled necessary permissions.
This example is from the official facebook documentation, try it (execute publishStory() in your app):
private void publishStory() {
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("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
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();
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
The code issues a POST to the users feed wall with the graph params specified at the bundle.
If session does not have the needed publish permissions, then a permission request will be issued instead. If user granted those permissions, then the RequestAsyncTask should be executed next time you call the method.
As you can see the basic idea is to get the user to log-in with his facebook account (first step), then request necessary permissions for the action, in this case, publish permissions for a wall post (second step), and lastly issue a graph request into "me/feed" with the params needed for the wall post.
In any case, if you still encountering problems please try to debug from your log as it indicates wether the request failed because of invalid session or no permissions etc...
Post your log here in that case , but this should work.

Categories

Resources