I am creating an app in which I want to integrate facebook sdk. I want to login user with facebook, but it's creating problem.
It's working only one time. If I install the app and login with facebook it's working but when I uninstall my app and try to install and login again with facebook it's not working. It is not asking for access permission and doing nothing.
I want to ask one more question, I want to make custom facebook login button and after successfully login go to next Activity.
Here what I have already done. I don't know where is mistake?
Here is my main xml:
<ImageButton
android:id="#+id/btnFblogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:onClick="onClick"
android:src="#drawable/fb_signin" />
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
Here is my fragment :
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
btnFbLog = (ImageButton) view.findViewById(R.id.btnFblogin);
btnFbLog.setOnClickListener(this);
return view;}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnFblogin:
mSignInClicked = true;
Toast.makeText(getApplicationContext(), "Clicked on facebook login", Toast.LENGTH_SHORT).show();
fbloginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//updateFacebookButtonUI();
Profile profile = Profile.getCurrentProfile();
loginSocial(profile.getId(), Const.SOCIAL_FACEBOOK);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
public void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
private void loginSocial(String id, String loginType) {
if (!AndyUtils.isNetworkAvailable(activity)) {
AndyUtils.showToast(getResources().getString(R.string.no_internet),
activity);
return;
}
AndyUtils.showCustomProgressDialog(activity,
getResources().getString(R.string.text_signin), false, null);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Const.URL, Const.ServiceType.LOGIN);
map.put(Const.Params.SOCIAL_UNIQUE_ID, id);
map.put(Const.Params.DEVICE_TYPE, Const.DEVICE_TYPE_ANDROID);
map.put(Const.Params.DEVICE_TOKEN,
new PreferenceHelper(activity).getDeviceToken());
map.put(Const.Params.LOGIN_BY, loginType);
new HttpRequester(activity, map, Const.ServiceCode.LOGIN, this);
}
You can easily create your custom facebook login button via com.facebook.login.LoginManager. Facebook button is only wrapper for this class.
Sample:
private void loginWithFacebook() {
if(AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile() != null) {
//logout
LoginManager.getInstance().logOut();
} else {
//login
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(ActivityLogin.this, "onSuccess: " + loginResult.getAccessToken().getUserId(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Toast.makeText(ActivityLogin.this, "onCancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(ActivityLogin.this, "onError: " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Related
I tried integrating login with facebook in android with calling registerCallBack from Facebook LoginButton and it worked perfectly. But I wanted to customize my facebook login button with an ImageButton, so I tried performClick() when clicking on my customized ImageButton as below
callbackManager = CallbackManager.Factory.create();
LoginButton btnSignInFacebook = findViewById(R.id.btn_social_sync_facebook);
List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
btnSignInFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
startActivity(new Intent(SocialAccountsSyncActivity.this, AccountInformationSignUpActivity.class));
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
//my customized imagebutton
case R.id.ib_social_sync_facebook:
btnSignInFacebook.performClick();
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
This kept giving me this error:
Unsupported get request. Object with ID '668803530142270' does not exist, cannot be loaded due to missing permissions, or does not support this operation.
Anyone knows the reason please help me with it. Thanks
I have a simple app, in which I am using facebook sdk to get user info. I am trying to share content by using ShareLinkContent.Builder but I am receving error:
onError:
{FacebookServiceException: httpResponseCode: -1, facebookErrorCode: 100, facebookErrorType: null, message: The parameter 'href' or 'media' is required}
Here is my MainActivity:
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(LOG_TAG, "success");
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "onError: ", error);
}
#Override
public void onCancel() {
Log.d(LOG_TAG, "cancel");
}
});
createPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent.Builder post = new ShareLinkContent.Builder();
post = post.setContentUrl(Uri.parse(""));
post.setContentTitle("");
shareDialog.show(MainActivity.this, post.build());
}
}
});
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
What happens is that, dialog does not appear and I get the above error in logcat.
UPDATE:
What I want:
Is it possible to use ShareLinkContent.Builder with a null setContentUrl, I just want my user to share his text not a link or something else. Is it possible?
I'm using Facebook SDK 4+ and my problem is that when i use
FacebookSdk.sdkInitialize(getApplicationContext());
LoginManager.getInstance().logOut();
to logout from my app it's not working correct. I return to my target activity with the login button. When i press the button i get in the app again without authorization. I have installed the native Facebook app. Without this app erverything is working fine. So what i'm doing wrong or im missing something.
The Api Key where ok and they are working.
my login implementaion is like:
private ImageButton loginButton;
private LoginButton fbbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
}
#Override
protected void onResume() {
super.onResume();
callbackManager= CallbackManager.Factory.create();
fbbtn= (LoginButton)findViewById(R.id.fb_button);
fbbtn.setReadPermissions("public_profile", "email","user_friends");
loginButton = (ImageButton) findViewById(R.id.login_btn);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
fbbtn.performClick();
fbbtn.setPressed(true);
fbbtn.invalidate();
fbbtn.registerCallback(callbackManager, mCallBack);
fbbtn.setPressed(false);
fbbtn.invalidate();
}
});
}
#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) {
app.setUser(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
To change user profile you need logged out from it in your FB app (or in Chrome if you are using Chrome Custom Tabs)
I''m following this Tutorial but so far I can't make it work, though this is from a year ago or so...
I'm using androidStudo 1.2.2 and FacebookSDK 4.
I want a simple login into facebook using a custom button, like the one shown in this image:
Now, in the example from the tutorial I'm having problems with the Session variable, it says it cannot resolve it, neither getActivity()
Has naybody tried this on FacebookSDK4.0?
Is that a correct approach or maybe there is something more updated?
Step 1:
First add FrameLayout and make facebook button visibility="gone" and add your custom button.
Don't forgot to put xmlns:facebook="http://schemas.android.com/apk/res-auto" in your main layout.
<FrameLayout
android:id="#+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<Button
android:id="#+id/fb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#416BC1"
android:onClick="onClick"
android:text="FaceBook"
android:textColor="#ffffff"
android:textStyle="bold" />
</FrameLayout>
Step 2:
Initialize FacebookSdk in onCreate before inflecting layout.
FacebookSdk.sdkInitialize(this.getApplicationContext());
Step 3: add this into your java file.
callbackManager = CallbackManager.Factory.create();
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity",
response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
Step 4:
Don't forget to add following code.
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
Step 5:
Set your custom button click to FacebookLogin button click.
public void onClick(View v) {
if (v == fb) {
loginButton.performClick();
}
}
Step 6:
For programmatically logout use this.
LoginManager.getInstance().logOut();
Step 7: you can find user logged in or not by profile.
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}
IMO part of the selected answer is kind of work-around not the proper solution.
So what needs to be changed to make it proper is the following:
Get rid of "com.facebook.login.widget.LoginButton" from your XML
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
Get rid of all references to the "LoginButton" in your Java code
Use Facebook's "LoginManager" class which is there for that purpose as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
// Some code
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(
callbackManager,
new FacebookCallback < LoginResult > () {
#Override
public void onSuccess(LoginResult loginResult) {
// Handle success
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
}
);
}
public void onClick(View v) {
if (v == fb) {
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("user_photos", "email", "user_birthday", "public_profile")
);
}
}
// this part was missing thanks to wesely
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
This is very simple.
Add a button in the layout file like
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Login with facebook"
android:textColor="#ffff"
android:layout_gravity="center"
android:textStyle="bold"
android:onClick="fbLogin"
android:background="#color/colorPrimary"/>
And in the onClick place the LoginManager's registercallback() method
Becuse the this method automatically executes.
like:
public void fbLogin(View view)
{
// Before Edit:
// LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts" , "AccessToken"));
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts"));
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
// App code
}
#Override
public void onCancel()
{
// App code
}
#Override
public void onError(FacebookException exception)
{
// App code
}
});
}
Have Fun
(don't have enough reputation to add a comment ...)
I tried the #Shehabix's answer, can't receive callback until I add this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
then it works fine.
The Simple answer is add facebookButton.performClick() inside cutomBtn.setOnClickListener
<!-- connect with Facebook -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textSize="#dimen/login_fb_font_size"
android:visibility="invisible" />
<LinearLayout
android:id="#+id/mfb_connect"
style="#style/facebook_button">
<ImageView
style="#style/login_connect_icon"
android:src="#drawable/ic_facebook" />
<TextView
style="#style/login_connect_text"
android:text="#string/login_connect_facebook" />
</LinearLayout>
</RelativeLayout>
...
private LoginButton fb_connect;
private LinearLayout mfb_connect;
...
// the button from facebook sdk
fb_connect = (LoginButton) findViewById(R.id.fb_connect);
// handle the click from my custom button to perfrom action click on facebook sdk button
mfb_connect = (LinearLayout) findViewById(R.id.mfb_connect);
mfb_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fb_connect.performClick();
}
});
That will achieve this:
i just call the facebook default button from my custom button and left every single line of code as documented. and bang it works successfully.
public class SignInFragment extends Fragment implements
FragmentChangeListener{
private Button facebook
private FirebaseAuth firebaseAuth;
private CallbackManager mCallBackManager;
private LoginButton loginButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
facebook = view.findViewById(R.id.facebookButton);
loginButton = view.findViewById(R.id.facebookBtn);
firebaseAuth = FirebaseAuth.getInstance();
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.callOnClick();
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallBackManager = CallbackManager.Factory.create();
loginButton.setFragment(SignInFragment.this);
loginButton.setPermissions("email","public_profile");
loginButton.registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getContext(),"Is Cancelled",Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
startActivity(new Intent(getContext(),MainActivity.class));
} else {
// If sign in fails, display a message to the user.
Toast.makeText(getContext(), task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Complementing the answers by Harvi and Shehabix, I would suggest to add this method as this registers the authentication in Firebase Auth.
This method should be called inside "On Success" of LoginManager.
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Toast.makeText(MainActivity.this, "Autenticando",Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
}
});
}
try this
// Facebook Button
LoginButton loginButton = findViewById(R.id.loginbtn);
loginButton.setVisibility(View.GONE)
// Your Custom Button
binding.fbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginButton.callOnClick();
}
});
Is there any tutorial or example showing how to login using own Button using Facebook SDK 4.0 in Android? I am not getting anywhere and using facebook developers site it is difficult to understand.Like below when calling FBlogin button I want to check go for login if user has not logged in or if logged in I want the access token to get facebook profile information and user likes.
FBlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Facebook login Code to get profile info and user likes
}
});
I have tried also loginButton Facebook.
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="244dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
/>
But it is showing error in xml :-
java.lang.NoClassDefFoundError: Could not initialize class com.facebook.login.widget.LoginButton
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:413)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:176)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:206)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:131)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:739)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:64)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:711)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:372)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:369)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:326)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
at com.android.tools.idea.rendering.RenderService$5.compute(RenderService.java:708)
at com.android.tools.idea.rendering.RenderService$5.compute(RenderService.java:697)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:932)
at com.android.tools.idea.rendering.RenderService.createRenderSession(RenderService.java:697)
at com.android.tools.idea.rendering.RenderService.render(RenderService.java:816)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:646)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.java:82)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.java:589)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:178)
at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:171)
at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.java:584)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
My Activity class:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Ia there any example/tutorial to login using facebook sdk4.0? I am stuck in both way. Please help.
This might help you
// Custom button
private Button fbbutton;
// Creating Facebook CallbackManager Value
public static CallbackManager callbackmanager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize SDK before setContentView(Layout ID)
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
// Initialize layout button
fbbutton = (Button) findViewById(R.id.button2);
fbbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFblogin();
}
});
}
// Private method to handle Facebook login and callback
private void onFblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email","user_photos","public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
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 str_email = json.getString("email");
String str_id = json.getString("id");
String str_firstname = json.getString("first_name");
String str_lastname = json.getString("last_name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).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);
}
In manifest add following,
<application
android:allowBackup="true"
android:icon="#drawable/app_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
.
.
<!-- [START Facebook] -->
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<!-- [END Facebook] -->
.
.
</application>
The best solution is to log in by using LoginManager. Here is how I managed this ( on click is made with ButterKnife ):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCallbackManager = CallbackManager.Factory.create();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginManager.getInstance().registerCallback(mCallbackManager, this);
}
#OnClick(R.id.facebook_login_button)
#SuppressWarnings("unused")
public void loginWithFacebookAccount() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
}
#Override
public void onSuccess(LoginResult loginResult) {
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,last_name,link,email,picture");
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), (jsonObject, graphResponse) -> {
String id = null;
if (jsonObject != null) {
try {
id = jsonObject.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
So this is how I've made it. Feel free to ask ;)
public class AuthWFacebookSDKFour extends Activity implements View.OnClickListener,FacebookCallback<LoginResult> {
List<String> permissionNeeds=Arrays.asList("user_photos","friends_photos", "email", "user_birthday", "user_friends");
//facebook callbacks manager
private CallbackManager cm;
private LoginButton mFbLoginButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init facebook sdk and
FacebookSdk.sdkInitialize(getApplicationContext());
//instantiate callbacks manager
mCallbackManager = CallbackManager.Factory.create();
mFbLoginButton=(LoginButton)findViewById(R.id.FBBUTTONID);
//set permissions mFbLoginButton.setReadPermissions(ApplicationContext.facebookPermissions);
// register callback
//means hey facebook after login call onActivityResult of **this**
mFbLoginButton.registerCallback(mCallbackManager, this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//manage login result
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSuccess(LoginResult loginResults) {
//login ok get access token
AccessToken.getActiveAccessToken();
}
#Override
public void onCancel() {
Log.e(TAG(),"facebook login canceled");
}
#Override
public void onError(FacebookException e) {
Log.e(TAG(),"facebook login failed error");
}
}
remember to insert in manifest
<activity
android:name="com.facebook.FacebookActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
/>
For Facebook SDK version 4.X,
In your activity or fragment (generally on onCreate() method):
// Initialize Facebook Sdk before UI
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.v(TAG, "fblogin onSuccess");
}
#Override
public void onCancel() {
// App code
Log.v(TAG, "fblogin onCancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v(TAG, "fblogin onError");
}
});
And also dont forget to pass facebook activity result to manager:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Using Android facebook SDK 4.X Login with faceboook Default Login_button
public class FbDefaultBtnLogin extends AppCompatActivity {
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_fb_default_btn_login);
callbackManager = CallbackManager.Factory.create();
// LoginButton loginButton=(LoginButton)findViewById(R.id.login_button);
LoginManager.getInstance().logInWithReadPermissions(this,Arrays.asList("email","user_photos","public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jitendra.facebooklogin.FbDefaultBtnLogin">
<!--<com.facebook.login.widget.LoginButton-->
<!--android:id="#+id/login_button"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="center_horizontal"-->
<!--android:layout_marginTop="30dp"-->
<!--android:layout_marginBottom="30dp" />
</RelativeLayout>
In Mainifest:-
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:theme="#style/AppTheme" >
</activity>
hi check this tutorial: click here
In this tutorial you can get latest Facebook SDK example with custom login and logout button logic.