如何从Firebase实时数据库中的子项获取父项值?

时间:2020-04-22 22:14:34

标签: android firebase firebase-realtime-database firebase-authentication

我正在尝试开发与学校相关的应用。这是我的数据库的图片。在我的代码中,我将schoolEmail作为字符串(即字符串email = iisd@gmail.com)。我想使用此字符串来了解此电子邮件所属的学校(在本例中为IISD),我想以字符串形式获取此值。

请看这张图片

enter image description here 1

这是我的代码

public class HomeScreen extends AppCompatActivity {

    TextView schoolName,schoolEmail,schoolPhone,schoolAddress;
    Button logoutSchool;
    DatabaseReference databaseReference;
    String email;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);
        schoolName = findViewById(R.id.schoolName);
        schoolEmail = findViewById(R.id.schoolEmail);
        schoolPhone = findViewById(R.id.schoolPhone);
        schoolAddress = findViewById(R.id.schoolAddress);
        logoutSchool = findViewById(R.id.loginSchool);
        databaseReference =         FirebaseDatabase.getInstance().getReference();
        email = "iisd@gmail.com";

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                DataSnapshot dataSnapshot1 = dataSnapshot.getChildren();
                String value = dataSnapshot.child("Schools").getKey();

                Toast.makeText(HomeScreen.this, value, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(DatabaseError error) {

            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

        databaseReference.child("Schools").orderByChild("schoolEmail").equalTo("iisd@gmail.com").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    String value = ds.getKey();
                    Toast.makeText(HomeScreen.this, value, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                throw databaseError.toException();
            }
        });

这里的引用位于节点Schools上,然后使用查询orderByChild("schoolEmail").equalTo("iisd@gmail.com")检查schoolEmail = email_value,然后使用for循环获取密钥。