如何使用条件获取子值(FIREBASE和SDK)

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

How i can get child value using condition (FIREBASE & SDK)

问题

我想要在我的登录页面上,通过电子邮件/密码登录用户,当"角色"等于"洪水受害者"时(另一个角色是"救援者"和"管理员")。洪水受害者页面是"HomeActivity.class",而救援者页面是"HomeRes.class"。

以下是我的LoginActivity代码:

LoginActivity:

mAuth.signInWithEmailAndPassword(userEmail, userPswd)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                //登录成功,更新UI显示已登录用户的信息
                Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();

                FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
                DatabaseReference reference = firebaseDatabase.getReference().child("User");

                //检查用户是否已成功注册

                reference.orderByChild("userName").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (snapshot.exists()) {
                            Log.d("用户存在", "欢迎!");
                            String value = snapshot.child("userRole").getValue().toString();

                            if (value.equals("Flood Victim") && value != null) {
                                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                finish();
                            } else if (value.equals("Rescuer")) {
                                startActivity(new Intent(LoginActivity.this, HomeRescuer.class));
                                finish();
                            } else {
                                startActivity(new Intent(LoginActivity.this, HomeFv.class));
                                finish();
                            }
                        }
                    }

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

            } else {
                //如果登录失败,向用户显示错误消息
                Toast.makeText(LoginActivity.this, "错误" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

如何使用条件获取子值(FIREBASE和SDK)

英文:

What I want to do for my Login page is log as user using email/password and when "role" is equal to flood victim (the other role is Rescuer and Admin). The Flood victim page is HomeActivity.class and the rescuer page is HomeRes.class.

Here is my code for loginActivity:

LoginAcitivty:

  mAuth.signInWithEmailAndPassword(userEmail, userPswd)
.addOnCompleteListener(this, new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
if (task.isSuccessful()) {
//Sign in success, update UI with the signed-in user&#39;s information
Toast.makeText(LoginActivity.this, &quot;Login Successfull!&quot;,Toast.LENGTH_SHORT).show();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference().child(&quot;User&quot;);
//check if user has success registered
reference.orderByChild(&quot;userName&quot;).equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener()  {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Log.d(&quot;User exists&quot;, &quot;Welcome!&quot;);
String value =  snapshot.child(&quot;userRole&quot;).getValue().toString();
if (value.equals(&quot;Flood Victim&quot;) &amp;&amp; value != null) {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
} else if (value.equals(&quot;Rescuer&quot;)) {
startActivity(new Intent(LoginActivity.this, homeRescuer.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this, homeFv.class));
finish();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {}
});
}else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, &quot;Error&quot; + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}

如何使用条件获取子值(FIREBASE和SDK)

答案1

得分: 0

当您执行针对Firebase数据库的查询时,可能会有多个结果。因此,快照包含这些结果的列表。即使只有一个结果,快照也将包含一个结果的列表。

您的 onDataChange 需要通过循环遍历快照的子项来处理这个列表。

reference.orderByChild("userName").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(@NonNull DataSnapshot snapshot) {
    for (DataSnapshot userSnapshot: snapshot.getChildren()) { // 循环遍历快照的子项
       String value = userSnapshot.child("userRole").getValue(String.class); // 获取 "userRole" 的值

        if ("Flood Victim".equals(value)) { // 如果值等于 "Flood Victim"
          startActivity(new Intent(LoginActivity.this, HomeActivity.class));
          finish();
       } else if ("Rescuer".equals(value)) { // 如果值等于 "Rescuer"
         startActivity(new Intent(LoginActivity.this, homeRescuer.class));
         finish();
       } else {
         startActivity(new Intent(LoginActivity.this, homeFv.class));
         finish();
       }
    }
  }

  @Override
  public void onCancelled(@NonNull DatabaseError error) {
    throw error.toException(); // 永远不要忽略错误
  }
});
英文:

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your onDataChange needs to handle this list by looping over the children of the snapshot it gets.

reference.orderByChild(&quot;userName&quot;).equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener()  {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot: snapshot.getChildren()) { // &#128072;
String value = userSnapshot.child(&quot;userRole&quot;).getValue(String.class); // &#128072; 
if (&quot;Flood Victim&quot;.equals(value)) { // &#128072;
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
} else if (&quot;Rescuer&quot;.equals(value)) { // &#128072; 
startActivity(new Intent(LoginActivity.this, homeRescuer.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this, homeFv.class));
finish();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException(); // &#128072; never ignore errors
}
});

huangapple
  • 本文由 发表于 2023年2月16日 04:30:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465153.html
匿名

发表评论

匿名网友

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

确定