Send a request with Facebook Data to Server in Android - android

I am new in Android Development, so please, don't consider my question a dumb one.
In my application I have authorization with email, Facebook and twitter. Email part is done, and now I am doing the Facebook authorization part using LoginManager. I reached to a point, where tapping on facebook icon, facebook authorization screen appears, user inserts his credentials, Facebook asks about permission to use the data of user. after it the screen closes and user returns to application Login screen. For email login, user's email and password are sent to server. in Facebook case I don't clearly understand what I should send and how should I do that. Here is my code, please someone help or hint - what I have not done correct ?
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFacebookLogin();
}
});
****
private void onFacebookLogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile", "user_birthday"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
Bundle parameters = new Bundle();
parameters.putString("fields", "id, email, first_name, last_name, gender, user_birthday");
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
System.out.println("ERROR");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String email = json.getString("email");
String id = json.getString("id");
String firstname = json.getString("first_name");
String lastname = json.getString("last_name");
String gender = json.getString("gender");
String birthdate = json.getString("user_birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("TAG_CANCEL", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("TAG_ERROR", error.toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackmanager.onActivityResult(requestCode, resultCode, data);

ok I got the question. when your facebook login is success. fetch all information you need for sign In. like fetch the email address. and for password you can set a parameter authByFacebook="true". hope this works for you.

try to put the intent for moving to the next page after facebook login success
like below given code
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
//Toast.makeText(LoginActivity.this, "on success", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("login_type", "facebook");
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this, getResources().getString(R.string.facebook_app_id));
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this, getResources().getString(R.string.facebook_app_id));
}

Related

Facebook Profile getName() on Android always returning null

My Facebook Login Activity if it helps:
public class LoginActivity extends AppCompatActivity {
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "user_friends");
final Intent myIntent = new Intent(this, MapsActivity.class);
if (isLoggedIn()) {
startActivity(myIntent);
finish();
return;
}
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "user_friends"));
startActivity(myIntent);
finish();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
});
}
private boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
}
and the code I'm using to attempt to get someone's first name from their ID:
new Profile(creatorId, null, null, null, null, null).getFirstName()
I have tried the getFirstName() call shown here in addition to getName() and both always return null. I thought having "public_profile" in my requested Facebook permissions would allow me to get someone's name in this way if they have authorized my app while logging in through Facebook. However, I did not always have "public_profile" in my requested Facebook permissions, but I have forced all users to re-login through Facebook to my app with this current code and permissions, so I thought this would fix this problem. Nevertheless, this function keeps returning null and I'm not sure why.
Also, creatorId may be the FB ID of a different user than the currently logged in FB user. (They will have authorized+used the app in the past, just not the currently logged in user on that Android device).
So, it seems that a Graph Request is necessary, even for public profile information. Here is the Graph Request I used to get the first name for a certain Facebook ID, creatorId:
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
creatorId,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
Log.e("creatorId's first name:", response.getJSONObject().getString("first_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle params = new Bundle();
params.putString("fields", "id,first_name");
request.setParameters(params);
request.executeAsync();
You can use this code.
please change your GraphRequest.GraphJSONObjectCallback() interface
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
try {
Log.e(TAG,"id"+user.optString("id"));
Log.e(TAG,"id"+user.optString("first_name"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name");
request.setParameters(parameters);
request.executeAsync();`

Can not login through Facebook app in Android

I am creating a Facebook login method for my Android app. I am using my custom login button. This works fine when Facebook app is not installed and I have to manually login through the interface that appears after touching login button. The problem I am facing is, this method does not work properly when Facebook app is installed. In this case, when I touch login button, it starts that black and white circular loader with caption "Loading" and that loader continues forever. No login takes place. How do I go about solving it? Following is the code implemented.
Inside onCreate method
callbackManager=CallbackManager.Factory.create();
loginButton= (LoginButton)findViewById(R.id.login_button);
btnFBLogin= (TextView) findViewById(R.id.btnFBLogin);
btnFBLogin.setSelected(true);
btnFBLogin.startAnimation(animationButtonFadeIn);
btnFBLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
Inside Remaining Methods
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
btnFBLogin.setVisibility(View.GONE);
user = new User();
facebook_id = object.getString("id").toString();
user.uniqueID = facebook_id;
full_name = object.getString("name").toString();
user.name = full_name;
try{
email = object.getString("email").toString();
}catch (Exception e){
email = "email_not_provided";
}finally {
user.email = email;
}
PrefUtils.setCurrentUser(user, LoginActivity.this);
userRecord(facebook_id, full_name, email, "fb", null);
}catch (Exception e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
That means you have not entered your key hash properly.
See this issue : Android facebook login not working with installed Facebook app

how to avoid my app from starting automatically when i start facebook app

i created an app where users can log in via facebook login button. the problem is - whenever i start the facebook app on the phone, it automatically starts the other app, too and logs the user in. any idea how to avoid this?
here is my login action for facebook:
fbLoginButton.setReadPermissions("user_friends");
// Callback registration
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.v("STATUS", loginResult.getAccessToken().toString());
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
String facebookID = object.getString("id").toString();
String email = object.getString("email").toString();
String name = object.getString("name").toString();
//PrefUtils.setCurrentUser(user,LoginActivity.this);
String[] nameArray = name.split(" ");
String firstname = nameArray[0];
String lastname = nameArray[1];
Log.v("FIRSTNAME", firstname);
if(response.getError() == null) {
new FBLogin().execute(email, firstname, lastname, facebookID);
}
Log.v("FBEMAIL", object.toString());
}catch (Exception e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("im in", "2");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("im in", "3");
}
});
// catches fb login callback
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Do i have to log the user out in some special way with my logout button? till now on logout it just redirects back to my main activity and the user has to logout manually by clicking on the fb button. i'm confused and google couldn't help me out yet...

Android Facebook SDK 4.0 Login without Facebook App

I'm having issues with the webview login for Facebook on Android.
I've followed the tutorials and login works perfectly when the user has the Facebook app installed. When the Facebook app is not installed, the webview for facebook login pops up; however, after logging in and accepting the permissions, the webview simply redirects back to the login screen. It never goes back to my app.
Has anyone else encountered this problem?
FacebookSdk.sdkInitialize(this);
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
if (profile2 != null) {
loggedIn(profile2);
} else {
loggedOut();
}
}
};
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
Profile.fetchProfileForCurrentAccessToken();
}
};
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
getProfileInfo();
}
#Override
public void onCancel() {
// App code
Log.e("Facebook Login", "Login Cancelled");
loggedOut();
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook Login", "Failed to Login " + exception.toString());
loggedOut();
}
});
Looking at the logs without filters while the login takes place, I see a couple of possibly relevant logs.
I/chromium﹕ [INFO:CONSOLE(0)] "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.", source: (0)
I/Auth.Core﹕ [TokenCache] Missing snowballing token: no granted scopes set.
What was causing the problem was that I was overriding the onclicklistener of the login button to call the login function of the LoginManager. Just don't.
I think you forgot to use callbackManager for proper workflow. Used CallbackManager for registration callback must be called in onActivityResult of host activity. Activity should not be in singleInstance launchMode because it will not be able to launch startActivityForResult(facebook internally launches FacebookActivity using this method).
So add to your activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Given your description, I am imagining that you either are not connected on the internet or that you are not handling the login callbacks.
Here is a full facebook 4.0.+ login example.
Edit Based on your code:
You need to use FacebookSdk.sdkInitialize(this); before setContentView().
This is a working example without using Facebook app and if you close your app and open it again you'll be logged in automatically unless you log out.
Here we get the user email address and friends list after log in.
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private static final String TAG = "logTag";
private TextView mFriend, mEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
mFriend = (TextView) findViewById(R.id.tv_friend);
mEmail = (TextView) findViewById(R.id.tv_email);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "Successful Login");
GraphRequest friendsRequest = GraphRequest.newMyFriendsRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray objects, GraphResponse response) {
String x = objects.opt(0).toString();
mFriend.setText(x);
}
});
GraphRequest meRequest = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = response.getJSONObject().getString("email").toString();
mEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email, gender");
meRequest.setParameters(parameters);
meRequest.executeAsync();
parameters = new Bundle();
parameters.putString("field", "user_friends");
friendsRequest.setParameters(parameters);
friendsRequest.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "Login Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "Login Error");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// manage login results
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Response code 200 from facebook

I'm developing new android app which uses facebook sdk. I want to fetch users friends list, I'm doing it like that:
Request request = Request.newMyFriendsRequest(
Session.getActiveSession(),
new Request.GraphUserListCallback() {
public void onCompleted(List<GraphUser> paramAnonymousList,
Response paramAnonymousResponse) {
Toast.makeText(getApplicationContext(),
paramAnonymousList.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, paramAnonymousList.toString()
+ paramAnonymousResponse.toString());
}
});
request.executeAsync();
However when I run app I'm getting something like that:
GraphObjectList{itemType=GraphUser, state=[]}{Response: responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[]}}, error: null, isFromCache:false}
I tried to run this code inside app which is not in development mode and it's working fine - i'm able to fetch user's data. What can be the cause of response code 200. According to that: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0 response code 200 belong to facebook permission errors. But to fetch user's friends list I don't have to provide any specific permissions, so what can be the cause of this response?
Thanks in advance
HTTP 200 means that your request is OK.
The real issue is Facebook API v2.0. Apps cannot retrieve the full list of friends for a user, only friends already using the application. Even if you application is still in v1.0, users who first logged in after May 1st are getting v2.0 behaviour.
Reference: https://developers.facebook.com/docs/graph-api/reference/v2.0/user/friends
Cheers!
I have done in this way and works fine perfectly in Facebook SDK 4.18.0
public class SignIn extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//before set conteview
FacebookSdk.sdkInitialize(getApplicationContext());
// AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_signin);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest graphRequest=GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
Log.d("Graph Response",graphResponse.toString());
String myCustomizedResponse = graphResponse.getJSONObject().toString();
Log.d("Ketan_Ramani",graphResponse.getJSONObject().toString());
try {
JSONObject obj = new JSONObject(myCustomizedResponse);
String id = obj.getString("id");
String first_name = obj.getString("first_name");
String last_name = obj.getString("last_name");
String email = obj.getString("email");
Log.d("Id",id);
Log.d("FirstName",first_name);
Log.d("LastName",last_name);
Log.d("Email",email);
} catch (JSONException e) {
Utils.hide_dialog();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Categories

Resources