无法将通过身份验证的用户数据保存到Firebase

时间:2018-10-17 11:00:03

标签: android firebase firebase-realtime-database

我想将经过身份验证的用户的数据保存在Firebase中,有两种方法可以在我的应用程序中对数据进行身份验证,然后将用户带到MainActivity.Java。我想查看用户是否是第一次使用该应用程序,如果是的话,请将详细信息添加到Firebase RealtimeDatabase中的用户树中。

到目前为止,在添加用户注释下方的OnCreate中添加代码后,该应用程序不会崩溃或出现任何错误,但它也不会命中Firebase数据库并对其进行更新。

这是我的MainActivity.Java的OnCreate部分的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Carousel

        customCarouselView = findViewById(R.id.customCarouselView);

        customCarouselView.setPageCount(sampleImages.length);
        customCarouselView.setSlideInterval(4000);


        customCarouselView.setImageListener(imageListener);

        customCarouselView.setImageClickListener(new ImageClickListener() {
            @Override
            public void onClick(int position) {
//                Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
                redirectToHotDeals();
            }
        });

        // -- Carousel


        FirebaseAuth.getInstance().getCurrentUser();


        if (FirebaseAuth.getInstance().getCurrentUser() != null) {
            // User is signed in.
            String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
            String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
            String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

            NavigationView navigationView = findViewById(R.id.nav_view);
            View headerView = navigationView.getHeaderView(0);
            TextView navUsername = headerView.findViewById(R.id.emailText);
            TextView navUID = headerView.findViewById(R.id.uid);
            navUID.setText("ID: " + uid.substring(0, 10));
            navUsername.setText(email);


        } else {
            // No user is signed in.
            redirectToLogin();
        }

        // Action Bar

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Coupons List");

        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);

        // Set Layout
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Send Query to Firebase Db
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mRef = mFirebaseDatabase.getReference("Data");

        // Add User to DB or Update it
        String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
        String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
        User user = new User(name, email);
        mRef.child("User").child(fUser.getUid()).setValue(user);


        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

这是Firebase数据库的图像:我希望第一个孩子有UID,然后是电子邮件,并作为孩子的联系人。 enter image description here

这是我的User.Java

public class User {
    public String name, email, phone;

    public User(String name, String email){

    }

    public User(String name, String email, String phone) {
        this.name = name;
        this.email = email;
        this.phone = phone;
    }
}

2 个答案:

答案 0 :(得分:0)

首先为head复制声明。在您的NavigationView中定义如下:

onCreate()

然后;

navigationView = findViewById(R.id.nav_view);

关于Firebase数据集,NavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { ... 节点似乎不是User的子节点,您像这样声明了它:

Data

相反,请尝试以下操作:

mRef = mFirebaseDatabase.getReference("Data");
mRef.child("User").child(fUser.getUid()).setValue(user);

请注意,我们需要确保mRef = mFirebaseDatabase.getReference("User"); mRef.child("UID").setValue(user); 节点是此处的引用。似乎还有另一个根引用,我们需要检查整个结构,但我只是向您提供了如何获取和设置数据的路径。

但是,正如documentation所说,您需要得到已登录身份验证才能使用Firebase数据库 update-remove 等。否则,您应该更改规则以将其打开以供所有人进行编辑或其他操作。

答案 1 :(得分:0)

您可以使用这段代码来更新数据库中的值:

AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
        mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){
                    Log.d("Tag","SignInWithCredential: success");

                    FirebaseUser fUser = mAuth.getCurrentUser();
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
                    assert fUser != null;
                    User user = new User(fUser.getDisplayName(),fUser.getUid());
                    ref.child("users").child(fUser.getUid()).setValue(user);

                }
                else{
                    Log.w("TAG","SignInWithCredential: failure", task.getException());
                    Toast.makeText(MainActivity.this,"Authentication failed", Toast.LENGTH_SHORT).show();

                }
            }
        });