JAVA Android Studio 不向 Firebase 实时数据库发送数据

Posted

技术标签:

【中文标题】JAVA Android Studio 不向 Firebase 实时数据库发送数据【英文标题】:JAVA Android studio Doesn't send data to Firebase Realtime Database 【发布时间】:2021-10-23 03:31:09 【问题描述】:

我想在创建新帐户时将数据发送到我的实时数据库。创建新帐户我会看到它在身份验证中添加了新帐户,但在我的实时数据库中它没有添加任何内容。

在调试时,我看到控制台中的 Log.d(TAG, "onDataChange: Continue..."); 没有显示,并且没有显示任何内容。

我正在关注这个教程https://www.youtube.com/watch?v=zPYqEpbihCs&list=PLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv&index=28

数据库结构: enter image description here

注册活动.java 将数据发送到 Firebase 数据库的代码

private void setupFirebaseAuth()
    Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");

    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();

    mAuthListener = new FirebaseAuth.AuthStateListener() 
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) 
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user != null) 
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                myRef.addListenerForSingleValueEvent(new ValueEventListener() 
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) 
                        Log.d(TAG, "onDataChange: Continue...");
                        //1st check: Make sure the username is not already in use
                        if(firebaseMethods.checkIfUsernameExists(username, 
                        dataSnapshot))
                            append = myRef.push().getKey().substring(3,10);
                            Log.d(TAG, "onDataChange: username already exists.    
                            Appending random string to name: " + append);
                        
                        username = username + append;

                        //add new user to the database
                        firebaseMethods.addNewUser(email, username, "", "", "");

                        Toast.makeText(mContext, "Signup successful. Sending 
                        verification email.", Toast.LENGTH_SHORT).show();

                    

                    @Override
                    public void onCancelled(DatabaseError databaseError) 

                        Log.d(TAG, "onCancelled: Cancelled ");
                        Log.e(TAG, "Failed to read    
                        value.",databaseError.toException());
                    
                );

             else 
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            
            // ...
        
    ;

我使用另一个文件来存储我的所有 FirebaseMethod 逻辑

package com.example.searchapp.Utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.searchapp.R;
import com.example.searchapp.login.RegisterActivity;
import com.example.searchapp.models.User;
import com.example.searchapp.models.UserAccountSettings;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.EmailAuthCredential;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class FirebaseMethods 

    private static final String TAG = "FirebaseMethods";

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private String userID;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;

    private Context mContext;

    public FirebaseMethods(Context context)
        mAuth = FirebaseAuth.getInstance();
        mContext = context;
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();


        if(mAuth.getCurrentUser() != null)
            userID = mAuth.getCurrentUser().getUid();
        
    
    public boolean checkIfUsernameExists(String username, DataSnapshot dataSnapshot)
        Log.d(TAG, "checkIfUsernameExists: check if " + username + "already exists");
        User user = new User();
//dataSnapshot.child(userID).getChildren()
        for(DataSnapshot ds: dataSnapshot.child(mContext.getString(R.string.dbname_users)).getChildren())
            Log.d(TAG, "checkIfUsernameExists: datasnapshot " + ds);

            user.setUsername(ds.getValue(User.class).getUsername());
            Log.d(TAG, "checkIfUsernameExists: username "+user.getUsername());

            if(StringManipulation.expandUsername(user.getUsername()).equals(username))
                Log.d(TAG, "checkIfUsernameExists: FOUND A MATCH "+ user.getUsername());
                return true;
            
        
        return false;

    
    public void registerNewEmail(final String email, String password, final String username)
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() 
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) 
                        Log.d(TAG, "onComplete: createUserWithEmail " + task.isSuccessful());

                        if(!task.isSuccessful())
                            Toast.makeText(mContext, R.string.auth_failed,Toast.LENGTH_SHORT).show();
                        
                        else if(task.isSuccessful())
                        
                            userID = mAuth.getCurrentUser().getUid();
                            Log.d(TAG, "onComplete: Authstate changed " +userID );
                        
                    
                );
    
    public void addNewUser(String email, String username,String description,String website,String profile_photo)

        User user = new User(userID,1,email,StringManipulation.condenseUsername(username));

        myRef.child(mContext.getString(R.string.dbname_users))
                .child(userID)
                .setValue(user);

        UserAccountSettings settings = new UserAccountSettings(
                description,
                username,
                0,
                0,
                0,
                profile_photo,
                username,
                website
        );
        myRef.child(mContext.getString(R.string.dbname_user_account_settings))
                .child(userID)
                .setValue(settings);
    


字符串文件

<resources>
    <string name="app_name">SearchApp</string>
    <string name="edit_profile">Edit Profile</string>
    <string name="sign_out">Sign Out</string>
    <string name="auth_failed">Failed to Authenticate</string>
    <string name="auth_success">Authenticate Success</string>
    <string name="dbname_users">users</string>
    <string name="dbname_user_account_settings">user_account_settings</string>
</resources>

【问题讨论】:

这段代码中到底有什么不符合您的预期?告诉我们共享代码有什么问题。你有什么错误吗? 【参考方案1】:

您不会在任何地方将 mAuthListener 附加到 Firebase,这意味着 Firebase 永远不会调用它。

您需要致电 addAuthStateListener 以使 Firebase 了解您的侦听器,例如:

FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);

【讨论】:

以上是关于JAVA Android Studio 不向 Firebase 实时数据库发送数据的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio Logcat 未通过 Wi-Fi 显示带有 ADB 的日志消息

Android Studio – 在 Mac OS 上通过 Wi-Fi 运行和调试构建 [重复]

Android Studio 中的半空格或半空格

android studio 怎么打开eclipse

Django Channels 不向 Android App 发送消息

java 将您的Wi-Fi网络添加到Android Things