I try to write an application that can log in facebook. I use easyfacebooksdk.jar like library to use your API, but I have problem with configuration. I post the follow image:
This is the facebook app that I have created:
I have obtained the key hash in this way from console:
I put this code here in key has field( i can't post the image because i don't have 10 reputation)
This is my code:
public class MainActivity extends Activity implements LoginListener {
private FBLoginManager fbManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
//change the permissions according to the function you want to use
String permissions[] = { "read_stream", "user_relationship_details",
"user_religion_politics", "user_work_history",
"user_relationships", "user_interests", "user_likes",
"user_location", "user_hometown", "user_education_history",
"user_activities", "offline_access" };
//change the parameters with those of your application
fbManager = new FBLoginManager(this, R.layout.activity_main,
"334014040053829", permissions);
if (fbManager.existsSavedFacebook()) {
fbManager.loadFacebook();
} else {
fbManager.login();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fbManager.loginSuccess(data);
}
public void loginFail() {
fbManager.displayToast("Login failed!");
}
public void logoutSuccess() {
fbManager.displayToast("Logout success!");
}
public void loginSuccess(Facebook facebook) {
//library use example
GraphApi graphApi = new GraphApi(facebook);
User user = new User();
try {
user = graphApi.getMyAccountInfo();
graphApi.setStatus("Post by app");
} catch (EasyFacebookError e) {
e.toString();
}
}
}
I obtain this error in emulator: app is misconfigured to facebook log in but i don't understand why... Someone can you help me?
Related
I'm using this for my Facebook log-in and sharing. I'm wondering if instead of opening a WebView that displays the log-in with Facebookis there a way when a User have already installed a Facebook app instead of opening the WebView it will opens the Facebook app? And when the User is already log-in in the Facebook App it will gets its credentials and log-in automatically in my app? I can't seem to find how to do this. Thank you in advantage.
Edit
I found out that my activityCode always return -1 instead of >= 0 that's why it always open the WebView instead of the app. And also found out that I need to enabled the Single Sign-On, I enabled the Single Sign-On but it still doesn't open the facebook app. Maybe it is because of FORCE_DIALOG_AUTH that always returns -1. I'm wondering if there is a default value instead of using FORCE_DIALOG_AUTH.
In solution on the FORCE_DIALOG_AUTH I used code below:
Instead of using
facebook.authorize(this, Constants.FACEBOOK_PERMISSIONS,
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
I used
facebook.authorize(this, Constants.FACEBOOK_PERMISSIONS, new LoginDialogListener());
where in my Facebook.java
public void authorize(Activity activity, String[] permissions,
final DialogListener listener) {
authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}
Also it detects now if there is an Facebook app installed or not, but when there is an Facebook app installed it still doesn't display/open in Facebook app, it just load and goes back to my Activity nothing happens.
Update
I tried to log in without a user log-in in the Facebook app and that user is still not authorized to use my app, it opens the Facebook app log-in screen but after authorizing it, it doesn't get my log-in informations.
Here's my code in Facebook.java it same as it is
private boolean startSingleSignOn(Activity activity, String applicationId,
String[] permissions, int activityCode) {
boolean didSucceed = true;
Intent intent = new Intent();
intent.setClassName("com.facebook.katana",
"com.facebook.katana.ProxyAuth");
intent.putExtra("client_id", applicationId);
if (permissions.length > 0) {
intent.putExtra("scope", TextUtils.join(",", permissions));
}
// Verify that the application whose package name is
// com.facebook.katana.ProxyAuth
// has the expected FB app signature.
if (!validateActivityIntent(activity, intent)) {
return false;
}
mAuthActivity = activity;
mAuthPermissions = permissions;
mAuthActivityCode = activityCode;
try {
activity.startActivityForResult(intent, activityCode);
} catch (ActivityNotFoundException e) {
didSucceed = false;
}
return didSucceed;
}
In my activity that calls the authorizing and handles what to do after authorizing here's my code
private void setFacebookConnection() {
// progressBar.setVisibility(View.VISIBLE);
facebook = new Facebook(Constants.FACEBOOK_APP_ID);
facebookAsyncRunner = new AsyncFacebookRunner(facebook);
// facebook.authorize(MerchantDetailsActivity.this, Constants.FACEBOOK_PERMISSIONS,
// Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
facebook.authorize(MerchantDetailsActivity.this, Constants.FACEBOOK_PERMISSIONS, new LoginDialogListener());
}
private class LoginDialogListener implements Facebook.DialogListener {
public void onComplete(Bundle values) {
String token = facebook.getAccessToken();
long token_expires = facebook.getAccessExpires();
Log.d(TAG, "AccessToken: " + token);
Log.d(TAG, "AccessExpires: " + token_expires);
facebookSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
facebookSharedPreferences.edit()
.putLong(Constants.FACEBOOK_ACCESS_EXPIRES, token_expires)
.commit();
facebookSharedPreferences.edit()
.putString(Constants.FACEBOOK_ACCESS_TOKEN, token).commit();
facebookAsyncRunner.request("me", new IDRequestListener());
shareFBPost();
}
It seems that when the user is already authorized it doesn't go inside my LoginDialogListener
If you will use this guide you will be able to open Facebook app for login
After implementing Facebook auth, initialize Facebook SDK in your Application class or in activity which uses Facebook login
// initialize facebook sdk and app events logger
FacebookSdk.sdkInitialize(getApplicationContext());
Then you can use the class below to login
public class FacebookAuth {
private static FacebookAuth instance;
private OnLoginDataReadyListener mResponseListener;
public static synchronized FacebookAuth getInstance() {
if (instance == null) {
instance = new FacebookAuth();
}
return instance;
}
/**
* Call if you want the user to login with his facebook account
* #param activity needed to initialize the Facebook LoginManager
* #param listener used to set the login listener
*/
public void facebookLogin(Activity activity, OnLoginDataReadyListener listener, CallbackManager callbackManager) {
mResponseListener = listener;
LoginManager.getInstance().logInWithReadPermissions(activity, Arrays.asList("public_profile", "user_friends", "email"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getUserData();
}
#Override
public void onCancel() {
if (mResponseListener != null) {
mResponseListener.onCanceled();
}
}
#Override
public void onError(FacebookException error) {
if (mResponseListener != null) {
mResponseListener.onCanceled();
}
}
});
}
/**
* Creates an Facebook Graph request witch will grab the user data
* such as name id and picture for now
*/
public void getUserData() {
GraphRequest request = GraphRequest.newMeRequest( AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (mResponseListener != null) {
mResponseListener.onLoginDataReady(object);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "picture.height(200).width(200),cover,location,birthday,first_name,last_name,email,gender,name");
request.setParameters(parameters);
request.executeAsync();
}
public interface OnLoginDataReadyListener {
void onLoginDataReady(JSONObject facebookData);
void onCanceled();
}
}
Once you've implemented the above solution, în your activity create a CallbackManager
CallbackManager mCallbackManager = CallbackManager.Factory.create();
Then in button click listener you can login your user as following
FacebookAuth.getInstance().facebookLogin(activity, dataReadyListener, mCallbackManager);
And finally in onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
Hope this will help you ))
I use the latest Facebook SDK instead and follow these steps. It is important to add onActivityResult for Facebook login callbackManager.
I was able to implement the the facebook login using the code :
public class MainActivity extends ActionBarActivity implements FacebookCallback<LoginResult> {
//List<String> permissionNeeds=Arrays.asList("user_photos","friends_photos", "email", "user_birthday", "user_friends");
TextView t;
String get_id, get_name, get_gender, get_email, get_birthday, get_locale, get_location;
private CallbackManager mCallbackManager;
private LoginButton mFbLoginButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init facebook sdk and
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
//instantiate callbacks manager
mCallbackManager = CallbackManager.Factory.create();
mFbLoginButton=(LoginButton)findViewById(R.id.login_button);
mFbLoginButton.registerCallback(mCallbackManager, this);
mFbLoginButton.setReadPermissions(Arrays.asList("user_status","email"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//manage login result
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
public void onSuccess(LoginResult loginResults) {
Toast.makeText(getApplicationContext(), "Success ",
Toast.LENGTH_LONG).show();
}
public void onCancel() {
}
public void onError(FacebookException e) {
}
}
Now how can I get the user details such as name , email ,age ,etc .I have searched the web for a few examples but i was unsuccessful.Where am i supposed to put the code for it ?
To do this you can use this.
//add variable names.
private static String uid,email;
public void getuserdata() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.v("LoginActivity", response.toString());
try {
//and fill them here like so.
uid = object.getString("id");
email = object.getString("email")
} catch (JSONException e) {
e.printStackTrace();
}
getGroups();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
And to use this just call getuserdata() in your on create for example.
I'm creating a library to implement a Facebook login without having to compile FacebookSDK directly in the project using the library, meaning, the library (i.e. FacebookLogingUtils) compiles the Facebook SDK and uses its methods to create simpler methods for a programmer to implement Facebook login. The programmer won't ever have to compile Facebook SDK since everything dealing with it is managed within the library.
The issue is the following one: I want to provide the user with a button which they can call in their layout file instead of FacebookLogginButton, so once the button is received by the library, it will be converted into a Facebook.LoginButton and can be used as such. How can I do this? How can I change a button I receive as a parameter into a different kind of button and return it?
You don't have use the LoginButton class to perform a login. You can just use the LoginManager, and trigger a login anytime by using .loginWith(). To see an example of it can be done, check this answer: https://stackoverflow.com/a/30230718/1395437
Now FB gives provision in their 4.x SDK to do like this without using the FB Login Button.
Please try following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
protected void doFBLoginForProfile() {
LoginManager loginManager = LoginManager.getInstance();
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
fetchUserInfo();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
loginManager.logInWithReadPermissions(this, getReadPermissions());
}
private ArrayList<String> getReadPermissions() {
ArrayList<String> fbPermissions = new ArrayList<String>();
fbPermissions.add("public_profile");
fbPermissions.add("email");
fbPermissions.add("user_location");
fbPermissions.add("user_friends");
return fbPermissions;
}
public void fetchUserInfo() {
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Utils.displayLogs("FB", "response: " + object);
onFBUserInfoFetched(new FBProfile().parse(object));
}
}).executeAsync();
}
public class FBProfile {
public String id = "";
public String email = "";
public String firstName = "";
public String lastName = "";
public String location = "";
public FBProfile parse(JSONObject object) {
id = object.optString("id");
email = object.optString("email");
firstName = object.optString("first_name");
lastName = object.optString("last_name");
if (object.has("location")) {
location = object.optJSONObject("location").optString("name");
}
return this;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The question in github
I'm using android-simple-facebook lib to make login in facebook and get some user data.
In this case the problem that I'm facing is that I can't get the user's birthdate data.
I've set the permissions to the SimpleFacebookConfiguration object
private Permission[] permissions = new Permission[]{
Permission.EMAIL,
Permission.USER_BIRTHDAY,
Permission.PUBLIC_PROFILE,
Permission.PUBLISH_ACTION
};
and this profile's permissions to get the data
Profile.Properties properties = new Profile.Properties.Builder()
.add(Profile.Properties.ID)
.add(Profile.Properties.FIRST_NAME)
.add(Profile.Properties.LAST_NAME)
.add(Profile.Properties.BIRTHDAY)
.add(Profile.Properties.AGE_RANGE)
.add(Profile.Properties.EMAIL)
.add(Profile.Properties.GENDER)
.build();
But I can't get the data from any of them. Any idea?
To request for new permission
private Permission[] permissions = new Permission[]{
Permission.EMAIL,
Permission.USER_BIRTHDAY,
};
SimpleFacebook.getInstance().requestNewPermissions(permissions, new OnNewPermissionsListener() {
#Override
public void onFail(String reason) {
//mResult.setText(reason);
System.out.println(""+reason);
}
#Override
public void onException(Throwable throwable) {
// mResult.setText(throwable.getMessage());
System.out.println(""+throwable.getMessage());
}
#Override
public void onCancel() {
}
#Override
public void onSuccess(String accessToken, List<Permission> acceptedPermissions, List<Permission> declinedPermissions) {
// showGrantedPermissions();
mSimpleFacebook.getProfile(properties, onProfileListener);
if (declinedPermissions != null && declinedPermissions.size() > 0) {
Toast.makeText(LoginActivity.this, "User declined few permissions: " + declinedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
}
});
Profile.Properties properties = new Profile.Properties.Builder()
.add(Profile.Properties.ID)
.add(Profile.Properties.FIRST_NAME)
.add(Profile.Properties.LAST_NAME)
.add(Profile.Properties.BIRTHDAY)
.add(Profile.Properties.AGE_RANGE)
.add(Profile.Properties.EMAIL)
.add(Profile.Properties.GENDER)
.build();
I'm using this code to post on Facebook, but it does not work with the official Facebook app because it tries to send as a link. Is there any way around this?
Intent s = new Intent(android.content.Intent.ACTION_SEND);
s.setType("text/plain");
s.putExtra(Intent.EXTRA_SUBJECT, "Quote");
s.putExtra(Intent.EXTRA_TEXT, qoute);
startActivity(Intent.createChooser(s, "Quote"));
It's a bug in the official facebook app. I had to code my own activity to do it using the Facebook SDK for Android. See the code sample below.
public class FacebookActivity extends Activity implements DialogListener
{
private Facebook facebookClient;
private LinearLayout facebookButton;
private final String APP_API_ID = "XXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
facebookClient = new Facebook();
// replace APP_API_ID with your own
facebookClient.authorize(this, APP_API_ID,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
#Override
public void onComplete(Bundle values)
{
if (values.isEmpty())
{
//"skip" clicked ?
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "post_id" is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("post_id"))
{
try
{
Bundle parameters = new Bundle();
parameters.putString("message", "YOUR TEXT TO SHARE GOES HERE");// the message to post to the wall
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
#Override
public void onError(DialogError e)
{
return;
}
#Override
public void onFacebookError(FacebookError e)
{
return;
}
#Override
public void onCancel()
{
return;
}
}