未从Firebase数据库获取到用户名。

huangapple go评论73阅读模式
英文:

Not getting username from Firebase database

问题

我的应用根据以下代码发送用户名:

mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new 
OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()){
            currentUserUid=mAuth.getCurrentUser().getUid();
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference myRef = database.getReference("MyUserList");
            
            myRef.child(usernameInput).child(currentUserUid).child("username").setValue(usernameInput);
            
            sendUserToLoginActivity();
            Toast.makeText(RegisterActivity.this, "Account Created Successfully", 
            Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();
        }
    }
});

现在我必须从Firebase数据库中的另一个活动中获取用户名。我尝试了以下方法,但每次传递到数据库的是“分数”,而不是用户名。我不想更改用户名设置方式(上面的代码),因为我在用户注册时检查重复的用户名。如何获取当前的用户名?

private String currentUserUid;
private FirebaseAuth mAuth;
private String name;

public void finisHere(){
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("Score");
    String key = myRef.push().getKey();

    //......................
    currentUserUid = mAuth.getCurrentUser().getUid();

    DatabaseReference cUserNameRef = database.getReference("MyUserList");

    cUserNameRef.child(currentUserUid).addListenerForSingleValueEvent(new 
    ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                name = dataSnapshot.child("username").getValue(String.class);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    
    savingScoreModel scoreModel = new savingScoreModel(score, name);
    myRef.child(key).setValue(scoreModel);
    Intent intent = new Intent(liveQuestionActivity.this, MainActivity.class);

    Toast.makeText(this, currentUserUid, Toast.LENGTH_SHORT).show(); //Toast is working
    startActivity(intent);
    finishAffinity();
}

我通过以下代码验证了重复的用户名。

private void DuplicateUserName(){
    final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference userNameRef = rootRef.child("MyUserList").child(usernameInput);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!dataSnapshot.exists()) {
                //create new user
                //Toast.makeText(RegisterActivity.this, "success", Toast.LENGTH_SHORT).show();
                CreateNewAccount();
            } else {
                UserName.setError("This username already taken");
                UserName.requestFocus();
                loadingBar.dismiss();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(RegisterActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    };
    userNameRef.addListenerForSingleValueEvent(eventListener);
}
英文:

My app is sending user name according to the below code

  mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new 
  OnCompleteListener&lt;AuthResult&gt;() {
                @Override
                public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                    if (task.isSuccessful()){


                        currentUserUid=mAuth.getCurrentUser().getUid();
                        FirebaseDatabase database = FirebaseDatabase.getInstance();
                        DatabaseReference myRef = database.getReference(&quot;MyUserList&quot;);
                        
  myRef.child(usernameInput).child(currentUserUid).child(&quot;username&quot;).setValue(usernameInput);

                        sendUserToLoginActivity();
                        Toast.makeText(RegisterActivity.this, &quot;Account Created Successfully&quot;, 
  Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();

                    }

Now i have to get the username from Firebase database in another activity. I have tried the below way but every time the 'score' is passing to database but not the username. I don't want change the username setting way (above code) because i am checking duplicate username on user registration. How can i get the current username?

  private String currentUserUid;
  private FirebaseAuth mAuth;
  private String name;



  public void finisHere(){

       
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference(&quot;Score&quot;);
         String key=myRef.push().getKey();

        //......................
        currentUserUid= mAuth.getCurrentUser().getUid();

        DatabaseReference cUserNameRef = database.getReference(&quot;MyUserList&quot;);

        cUserNameRef.child(currentUserUid).addListenerForSingleValueEvent(new 
 ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot:snapshot.getChildren()){
                   // String name=&quot;&quot;;
                    name=dataSnapshot.child(&quot;username&quot;).getValue(String.class);

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
        savingScoreModel scoreModel=new savingScoreModel(score,name);
        myRef.child(key).setValue(scoreModel);
        Intent intent =new 
        Intent(liveQuestionActivity.this,MainActivity.class);

        Toast.makeText(this, currentUserUid, Toast.LENGTH_SHORT).show(); //Toast is working
        startActivity(intent);
        finishAffinity();


    }

i am verifying the duplicate user name by the below code.

  private  void DuplicateUserName(){
        final DatabaseReference rootRef = 
 FirebaseDatabase.getInstance().getReference();
        DatabaseReference userNameRef = 
 rootRef.child(&quot;MyUserList&quot;).child(usernameInput);
        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(!dataSnapshot.exists()) {
                    //create new user
                    //Toast.makeText(RegisterActivity.this, &quot;success&quot;, 
 Toast.LENGTH_SHORT).show();
                   /* FirebaseDatabase database = 
 FirebaseDatabase.getInstance();
                    DatabaseReference myRef = 
 database.getReference(&quot;MyUserList&quot;);
                    
 myRef.child(usernameInput).child(&quot;username&quot;).setValue(usernameInput);

                    */
                    CreateNewAccount();


                }
                else {
                    UserName.setError(&quot;This username already taken&quot;);
                    UserName.requestFocus();
                    loadingBar.dismiss();
                }


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(RegisterActivity.this, 
databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        };
        userNameRef.addListenerForSingleValueEvent(eventListener);
    }

答案1

得分: 0

Username was Uploaded to &quot;MyUserList&quot;/usernameInput/currentUserUid/&quot;username&quot;

But you are fetching &quot;MyUserList&quot;/currentUserUid/&quot;username&quot;

So, try this for uploading:

myRef.child(&quot;MyUserList&quot;).child(currentUserUid).child(&quot;username&quot;).setValue(usernameInput);

Hope this helps. Feel free to ask for clarifications...

EDIT: Edited after @Farhad's doubts

DatabaseReference reference = database.getReference(&quot;MyUserList&quot;);

reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {

            //TODO: Here are your UserNames

        }
    }
    
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});
英文:

Username was Uploaded to &quot;MyUserList&quot;/usernameInput/currentUserUid/&quot;username&quot;

But you are fetching &quot;MyUserList&quot;/currentUserUid/&quot;username&quot;

So, try this for uploading:

myRef.child(&quot;MyUserList&quot;).child(currentUserUid).child(&quot;username&quot;).setValue(usernameInput);

Hope this helps. Feel free to ask for clarifications...

EDIT: Edited after @Farhad's doubts

DatabaseReference reference = database.getReference(&quot;MyUserList&quot;);

        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
                  
                    //TODO: Here are your UserNames

                    }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

huangapple
  • 本文由 发表于 2020年8月28日 02:03:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63621804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定