我想从Firebase数据库中获取一个值,并将其存储到字符串中,并且该值应该是当前用户的

时间:2019-12-26 11:51:20

标签: java android firebase firebase-realtime-database

this is the image of the datbase

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity">

 <TextView
    android:id="@+id/timeTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/time_text_view"
    android:text="2:10"
    android:textStyle="bold"
    android:textSize="40sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

<TextView
    android:id="@+id/timePostfixTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/time_text_view"
    android:text="PM"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintStart_toEndOf="@id/timeTextView"
    app:layout_constraintBottom_toBottomOf="@id/timeTextView" />
</androidx.constraintlayout.widget.ConstraintLayout> 

2 个答案:

答案 0 :(得分:1)

Firebase异步工作,因此您可以在过程完成时变量获取值。最好在onDataChange内开始调用,以便在变量检索值时可以将其发送到查询中。

public firebaseDatabaseHelpers() {
    mRef = FirebaseDatabase.getInstance().getReference("School_portal").child(FirebaseAuth.getInstance().getCurrentUser().getUid());

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
            public void onDataChange(DataSnapshot snapshot) {
                String value = document.getString("School_Verify_Key");
                mDatabase =FirebaseDatabase.getInstance();
                mReferenceteachers = FirebaseDatabase.getInstance().getReference("Teacher_portal")
                .orderByChild("School_Verify_Key").equalTo(value);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

}

答案 1 :(得分:1)

由于Firebase操作是异步的,请尝试将第二个查询放在onDataChange内部的数据库中。

public firebaseDatabaseHelpers() {
    mRef = FirebaseDatabase.getInstance().getReference("School_portal").child(FirebaseAuth.getInstance().getCurrentUser().getUid());

    mRef.child("School_Verify_Key").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            String value = snapshot.getValue(String.class);

            mReferenceteachers = FirebaseDatabase.getInstance().getReference("Teacher_portal")
                .orderByChild("School_Verify_Key").equalTo(value);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}