Any Example showing how to login using Facebook SDK 4.0 in Android either by using own button or Facebook Button?

42,919

Solution 1

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>

Solution 2

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 ;)

Solution 3

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"
                />

Solution 4

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);
}

Solution 5

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>
Share:
42,919

Related videos on Youtube

Rituraj Singh
Author by

Rituraj Singh

Updated on July 09, 2022

Comments

  • Rituraj Singh
    Rituraj Singh almost 2 years

    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.

    • Shadik Khan
      Shadik Khan about 9 years
      I think it will collapse the recent Facebook developer policy.
    • andyrandy
      andyrandy about 9 years
      what for do you need the user likes?
    • Rituraj Singh
      Rituraj Singh about 9 years
      @luschn I am making an educational project and want to extract some pattern using facebook likes of users.I will use the app for locally in the university campus to get likes of some of the users. If you have any tutorial regarding Facebook SDK4.0..please help
    • andyrandy
      andyrandy about 9 years
      i am not sure if you will get user_likes approved for that. although, you can just add everyone who takes part as tester.
    • ManishSB
      ManishSB over 8 years
      are you still searching for answer @RiturajSinghRathore
  • user2273146
    user2273146 about 9 years
    I keep on getting this error any idea what wrong going on "Unexpected call to LoginManager.onActivityResult"
  • ManishSB
    ManishSB about 9 years
    No its still giving the same error/exception, JSONexception/classnotfoundexception
  • Skynet
    Skynet about 9 years
    I thought Session is deprecated in 4.0
  • erdomester
    erdomester about 9 years
    It is. Did you find a tutorial? As usual, the developer site is not helping.
  • Jitendra Singh
    Jitendra Singh about 9 years
    Right Session was deprecated in 4.0. Again in 4.X you can use this. Check this edited answer.
  • ManishSB
    ManishSB almost 9 years
    @user2273146 try above answer, it might help you
  • shybovycha
    shybovycha almost 9 years
    You saved my day! None of SO answers mentions about translating activityResult to callbackManager...
  • gusridd
    gusridd almost 9 years
    this worked for me, I missed to add the onActivityResult method.
  • ManishSB
    ManishSB almost 9 years
    Oh @shybovycha, i am just doing my work, if you need anything more u can ask me here
  • Illusion
    Illusion almost 9 years
    I need your help. I want to retrieve user address as provided in api: developers.facebook.com/docs/android/graph#userdata-step3 but unable to get location json array in graph response.
  • Mariusz Brona
    Mariusz Brona almost 9 years
    Did you set "user_location" parameter?
  • Mantas
    Mantas almost 9 years
    @ManishSB I'm using your example but for some reason onActivityResult is not called and activity simply finishes. Do you have any idea what could be wrong?
  • ManishSB
    ManishSB almost 9 years
    please do share your code @Mantas, that is how i can help you out solve your problem
  • Mantas
    Mantas almost 9 years
    @ManishSB thanks for your effort but I have already sorted it out. The problem was that I had nohistory set to true for that activity.
  • Praveen
    Praveen over 8 years
    I was unable to retrieve email with this (sdk 4.5). To get email set parameters and pass it to GraphRequest (see Pan Wrona answer below)
  • Mostafa Addam
    Mostafa Addam over 8 years
    @ManishSB using your code above works fine but I'm not able to get other than the name and the id although i passing the permissions in the array list can u help me plz
  • Sunil Chaudhary
    Sunil Chaudhary over 8 years
    very Nice Thnx but now only getting error is this... starting with Graph API v2.4, GET requests for /me should contain an explicit "fields" parameter.(for email) can you pls help
  • Harsha
    Harsha over 8 years
    how to signout from the facebook login how to clear credintials and call login once again
  • Jitendra Singh
    Jitendra Singh over 8 years
    just call LoginManager.getInstance().logOut();
  • Stoycho Andreev
    Stoycho Andreev about 8 years
    The best decision is to use Facebook LoginManager object, not facebook login button. This answer is very good
  • iOSAndroidWindowsMobileAppsDev
    iOSAndroidWindowsMobileAppsDev almost 8 years
    Hi your tut runs just the first time, afte rwhich it always redirects to the login page & not the screen shown above. Could you please update your tut with code that works in your git repo github.com/niravkalola/FacebookLoginSample-master.