当前位置: 首页 > 知识库问答 >
问题:

如何在Android Studio中通过fragments和viewpager使用Facebook登录进行Firebase身份验证?

壤驷涛
2023-03-14

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

    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.myapplicationE/AndroidRuntime: FATAL EXCEPTION:主进程:jimmy.jimmyfindgymbuddyptl.com.myapplication, PID: 8439java.lang.RuntimeExc0019:无法启动活动ComponentInfo{jimmy.jimmyfindgymbuddyptl.com.myapplication/jimmy.jimmyfindgymbuddyptl.com.myapplication.MainActivity}:java.lang.在android.app.ActivityThread.perform启动活动(ActivityThread.java:2646)的空对象引用上,尝试调用虚拟方法“无效com.facebook.login.widget.LoginButton.set读取权限(java.lang.字符串[])”ActivityThread.handle启动活动(ActivityThread.java:2707)在android.app.ActivityThread.-wrap12(ActivityThread.java)在android.app.ActivityThread$H. handleMessage(ActivityThread.java:1460)在android.os.Handler.dispatch消息(Handler. java: 102)在android. os.在android. app.ActivityThread. main(ActivityThread. java: 6077)在java. lang.反射。方法调用(本机方法)在com. android. interal. os。ZygoteInit$method odAndArgsCaller. run(ZygoteInit. java: 866)在com. android. interal. os。ZygoteInit. main(ZygoteInit. java: 756)引起:java. lang.NullPointerExcture:尝试调用虚拟方法'无效com. facebook. login. widget。java. lang.字符串[])'在一个空对象引用在jimmy. jimmyfindymadddyptl. com. myApplication.在android. app.在android. app.在android. app.在android. app上的ActivityThread. performLaunch活动(ActivityThread. java: 2599)。处理启动活动(ActivityThread. java: 2707)

此按钮为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" />

共有3个答案

糜凯泽
2023-03-14

您可以使用Firebase Facebook身份验证。检查https://firebase.google.com/docs/auth/android/facebook-login留档

闻人宏盛
2023-03-14

我在同一个地方也犯了类似的错误。不确定这是否对您有帮助,但我忘了将我的内容视图设置为resources/layout文件夹中的facebook活动。

即。

在onCreate方法中。。。

setContentView(R.layout.activity_facebook);

我希望这能有所帮助。

周鸿运
2023-03-14

看起来您正在使用Firebase Auth的旧方法。最近在使用Firebase Auth SDK方面进行了更新,新方法非常简单,代码也非常少。请参阅此处了解更多详细信息https://firebase.google.com/docs/auth/android/firebaseui

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

// 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);
 类似资料:
  • 我试图用注册时使用的凭证登录。Firebase已经有注册用户的条目。每次我试图登录它显示“登录不成功”,我没有看到任何代码问题。请帮帮忙。

  • 使用,https://github.com/firebase/FirebaseUI-Android/tree/master/codelabs/chat作为登录的参考,我在键入时似乎遇到了问题 我只能键入Auth的提供者,而不能键入,为什么会这样,它提示我键入社会提供者。

  • 该应用程序应该接受用户电子邮件和密码,并使用Firebase身份验证作为后端。我使用像素2作为模拟器。每次应用程序处理登录功能时,它都会崩溃。 下面是Java文件和gradle文件 Java文件:

  • 我们目前正在从遗留安全子系统迁移到Elytron,并在JBoss EAP 7.3.6中部署了一个基于Struts2的web应用程序,该应用程序应该支持多种“风格”的身份验证。 登录的标准方式应该是,用户以登录表单()手动提供凭据,然后单击相应的按钮。这在我们的设置中与Elytron配合得很好。 第二种可能性是,对Web应用程序受保护内容的GET请求可能包含包含JWT令牌的自定义cookie。这个c

  • 我是Apache Shiro的新手,希望使用它的功能对我的RESTful web应用程序进行用户登录验证。我有一个允许用户登录的web表单。用户名和密码存储在MySQL数据库中。我有以下方法使用Jersey处理用户登录身份验证: 当我提交表单时,行导致错误。我想这是因为我还没有连接到我的数据库进行用户名和密码身份验证。但是我如何连接到我的后端数据库在Shiro中进行身份验证呢?我从Shiro的网站

  • 问题内容: 我一直在寻找一种让我的客户使用facebook JS SDK授权的方法,然后以某种方式将此授权转移到我的节点服务器(以便它可以使用fb graph api验证请求) 我偶然发现了:https : //github.com/jaredhanson/passport- facebook/issues/26 和 https://github.com/drudge/passport-faceb