简体   繁体   中英

How to Firebase Authenticate Using Facebook Login in Android Studio with fragments and viewpager?

My build completed successfully but the app crashed. Would someone write a tutorial on how to link Firebase Auth with Facebook Login in Android Studio using Viewpager and Fragments as in my code? I need a slider in my app.

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
 @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitenter code herey_main);
 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.

        mViewPager = (ViewPager) findViewById(R.id.container);
    enter code here
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mAuth = FirebaseAuth.getInstance();

        // Initialize Facebook Login button
        mCallbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = findViewById(R.id.login_button);

//Here problem start

        loginButton.setReadPermissions("email", "public_profile");

        loginButton.registerCallback(mCallbackManager, new 

FacebookCallback<LoginResult>() {

            @Override
    enter code here
            public void onSuccess(LoginResult loginResult) {

                Log.d(TAG, "facebook:onSuccess:" + loginResult);

               handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override

            public void onCancel() {

                Log.d(TAG, "facebook:onCancel");

                // ...
            }



            @Override

            public void onError(FacebookException error) {

                Log.d(TAG, "facebook:onError", error);

                // ...

            }
        });
// ...

    }

 @Override

    public void onStart() {

        super.onStart();

        // Check if user is signed in (non-null) and update UI accordingly.

        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser != null){
            updateUI();

        }
    }

    private void updateUI() {

        Toast.makeText(MainActivity.this, "You are logged in!" , 
Toast.LENGTH_LONG).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Pass the activity result back to the Facebook SDK
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + 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()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed."[enter image description here][1],
                                    Toast.LENGTH_SHORT).show();

                        }

                        // ...
                    }
                });
    }





/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = null;

        switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
            case 1:
            rootView = inflater.inflate(R.layout.fragment_main, container, false);



                break;

            case 2:
                rootView = inflater.inflate(R.layout.fragment_second, container, false);

                break;
        }

    return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */



public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;`enter code here`
    }
}

The app without fragments works perfectly. Does anybody have any idea why?

This is exception:

2019-01-19 11:13:05.129 8439-8439/jimmy.jimmyfindgymbuddyptl.com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: jimmy.jimmyfindgymbuddyptl.com.myapplication, PID: 8439 java.lang.RuntimeException: Unable to start activity ComponentInfo{jimmy.jimmyfindgymbuddyptl.com.myapplication/jimmy.jimmyfindgymbuddyptl.com.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.M ethod.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])' on a null object reference at jimmy.jimmyfindgymbuddyptl.com.myapplication.MainActivity.onCreate(MainActivity.java:92) at android.app.Activity.performCreate(Activity.java:6662) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.Acti vityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

this button was in xml:

<com.facebook.login.widget.LoginButton android:id="@+id/login_button" 
  android:layout_width="190dp" android:layout_height="wrap_content" 
  android:layout_above="@+id/textView7" android:layout_alignParentStart="true" 
  android:layout_marginStart="95dp" android:layout_marginBottom="6dp" />

It appears you're using older approach for Firebase Auth. There has been recent updates in using Firebase Auth SDK and the new approach is quite simple and minimal code. Please refer here for more details https://firebase.google.com/docs/auth/android/firebaseui

This is the approach to setup Facebook Auth provider and launch auth intent. You would need to add separate logic for Callaback handling and UI customization (if applicable) that too is available on above mentioned docs link. Please check it once, hope this would reduce your code and fix the issue too.

// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.FacebookBuilder().build());

// Create and launch sign-in intent
startActivityForResult(
        AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .build(),
        RC_SIGN_IN);

I had a similar error in the exact same place. Not sure if this will help you, but I forgot to set my content view to the facebook activity in the resources/layout folder.

ie

In the onCreate method...

setContentView(R.layout.activity_facebook);

I hope this helps.

You can use Firebase Facebook authentication. Check the documentation at https://firebase.google.com/docs/auth/android/facebook-login

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM