如何在Android Studio中使用带有片段和viewpager的Facebook登录进行Firebase身份验证?

问题描述 投票:0回答:3

我的构建成功完成,但应用崩溃。有人会像我的代码中那样编写有关如何使用Viewpager和Fragments将Firebase Auth与Android Studio中的Facebook Login链接的教程吗?我的应用程序中需要一个滑块。

    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`
    }
}

没有片段的应用程序完美运行。有人知道为什么吗?

这是例外:

2019-01-19 11:13:05.129 8439-8439 / jimmy.jimmyfindgymbuddyptl.com.myapplication E / AndroidRuntime:FATAL EXCEPTION:main流程:jimmy.jimmyfindgymbuddyptl.com.myapplication,PID:8439java.lang.RuntimeException:无法启动活动ComponentInfo {jimmy.jimmyfindgymbuddyptl.com.myapplication / jimmy.jimmyfindgymbuddyptl.com.myapplication.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法'void com.facebook.login。对空对象引用的widget.LoginButton.setReadPermissions(java.lang.String [])'在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)在android.app.ActivityThread.-wrap12(ActivityThread.java)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1460)在android.os.Handler.dispatchMessage(Handler.java:102)在android.os.Looper.loop(Looper.java:154)在android.app.ActivityThread.main(ActivityThread.java:6077)在java.lang.reflect.Method.invoke(本机方法)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String [])'在jimmy.jimmyfindgymbuddyptl.com.myapplication.MainActivity.onCreate(MainActivity.java:92)在android.app.Activity.performCreate(Activity.java:6662)在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)在android.app.ActivityThread.-wrap12(ActivityThread.java)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1460)在android.os.Handler.dispatchMessage(Handler.java:102)在android.os.Looper.loop(Looper.java:154)在android.app.ActivityThread.main(ActivityThread.java:6077)在java.lang.reflect.Method.invoke(本机方法)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)。

此按钮位于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" />
android facebook firebase android-fragments android-viewholder
3个回答
0
投票

[您似乎正在对Firebase Auth使用较旧的方法。使用Firebase Auth SDK已有最新更新,新方法非常简单且代码最少。请参阅此处以获取更多详细信息https://firebase.google.com/docs/auth/android/firebaseui

这是设置Facebook身份验证提供程序和启动身份验证意图的方法。您需要为Callaback处理和UI自定义添加单独的逻辑(如果适用),上述逻辑也可以在上述docs链接上获得。请检查一次,希望这将减少您的代码并解决此问题。

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

0
投票

我在完全相同的位置有一个类似的错误。不知道这是否对您有帮助,但是我忘记将我的内容视图设置为resources / layout文件夹中的facebook活动。

在onCreate方法中...

setContentView(R.layout.activity_facebook);

我希望这会有所帮助。


-1
投票

您可以使用Firebase Facebook身份验证。请查看https://firebase.google.com/docs/auth/android/facebook-login中的文档

© www.soinside.com 2019 - 2024. All rights reserved.