无法从从 FireBase 检索并显示在 setText 中的 class 获取值

Can't get value from class which is retrived from FireBase and display in a setText

我有一个包含 4 个卡片视图的网格布局,并且我在 firebase 数据库中有数据要显示在卡片中。从 Firebase 检索的数据存储在 class 中。问题是我不能使用 getter 函数并在 setText 中显示数据。每当我这样做时,应用程序就会崩溃。是一个片段。

这是片段:

public class HomeFragment extends Fragment {

usageData fetcheduserdata;
private DatabaseReference uidDatabase;
private DatabaseReference rootDatabase;
View v;
FirebaseAuth mAuth;
FirebaseUser mUser;
RecyclerView recyclerView;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_home,container,false);
    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    this.v = view;
    getActivity().setTitle("Home");

    mUser = mAuth.getInstance().getCurrentUser();

    TextView userPoints = (TextView) view.findViewById(R.id.user_points);
    TextView userAdrequests = (TextView) view.findViewById(R.id.user_adrequests);
    TextView userClicks =  (TextView) view.findViewById(R.id.user_adclick);
    TextView userRedeemthreshold =  (TextView) view.findViewById(R.id.user_rthreshold);



    final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    rootDatabase = FirebaseDatabase.getInstance().getReference();
    uidDatabase = rootDatabase.child("Data").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Integer up = dataSnapshot.child("userPoints").getValue(Integer.class);
            Integer ua = dataSnapshot.child("userAdrequests").getValue(Integer.class);
            Integer uc = dataSnapshot.child("userClicks").getValue(Integer.class);
            Integer ur = dataSnapshot.child("userRedeemthreshold").getValue(Integer.class);
            fetcheduserdata =  new usageData(uid,up,ua,uc,ur);
            Toast.makeText(getActivity(), "Fetched UsageData From Firebase", Toast.LENGTH_SHORT).show();

        }


        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(getActivity(), "UsageData Error", Toast.LENGTH_SHORT).show();
        }
    };

    uidDatabase.addValueEventListener(valueEventListener);
    userPoints.setText(String.valueOf(fetcheduserdata.getUserPoints()));
    userAdrequests.setText(fetcheduserdata.getUserAdrequests());
    userClicks.setText(fetcheduserdata.getUserClicks());
    userRedeemthreshold.setText(fetcheduserdata.getUserPoints());
}
}

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
tools:context=".HomeFragment">

<!-- TODO: Update blank fragment layout -->

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="2">


    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Your Performance"
        android:textSize="24sp"
        android:textStyle="italic" />
</RelativeLayout>


<GridLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8"
    android:alignmentMode="alignMargins"
    android:columnCount="2"
    android:columnOrderPreserved="false"
    android:padding="14dp"
    android:rowCount="2">

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_rowWeight="1"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <android.support.constraint.Guideline
                android:id="@+id/guideline"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.75" />

            <TextView
                android:id="@+id/user_points"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center_vertical|center_horizontal"
                android:text="0"
                android:textAlignment="center"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/guideline"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Points"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_rowWeight="2"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <android.support.constraint.Guideline
                android:id="@+id/guideline3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.75" />

            <TextView
                android:id="@+id/user_adrequests"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center_vertical|center_horizontal"
                android:text="0"
                android:textAlignment="center"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/textView6"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:gravity="center_horizontal"
                android:text="Ad Requests"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="2"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_rowWeight="1"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">


        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <android.support.constraint.Guideline
                android:id="@+id/guideline5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.75" />

            <TextView
                android:id="@+id/user_adclick"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center_vertical|center_horizontal"
                android:text="0"
                android:textAlignment="center"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/guideline5"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:gravity="center_horizontal"
                android:text="Ad Clicks"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent" />

        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="2"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_rowWeight="2"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <android.support.constraint.Guideline
                android:id="@+id/guideline6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_percent="0.75" />

            <TextView
                android:id="@+id/user_rthreshold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center_vertical|center_horizontal"
                android:text="0%"
                android:textAlignment="center"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/textView7"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:gravity="center_horizontal"
                android:text="Redeem Threshold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>
</GridLayout>

这是 class 使用数据:

package com.balaji.earnyourself;

public class usageData {
String userId;
Integer userPoints,userAdrequests,userClicks,userRedeemthreshold;

public usageData(String userId, Integer userPoints, Integer userAdrequests, Integer userClicks, Integer userRedeemthreshold) {
    this.userId = userId;
    this.userPoints = userPoints;
    this.userAdrequests = userAdrequests;
    this.userClicks = userClicks;
    this.userRedeemthreshold = userRedeemthreshold;
}

public usageData(String userId) {
    this.userId = userId;
    this.userPoints = 0;
    this.userAdrequests = 0;
    this.userClicks = 0;
    this.userRedeemthreshold = 0;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public int getUserPoints() {
    return userPoints;
}

public void setUserPoints(int userPoints) {
    this.userPoints = userPoints;
}

public int getUserAdrequests() {
    return userAdrequests;
}

public void setUserAdrequests(int userAdrequests) {
    this.userAdrequests = userAdrequests;
}

public int getUserClicks() {
    return userClicks;
}

public void setUserClicks(int userClicks) {
    this.userClicks = userClicks;
}

public int getUserRedeemthreshold() {
    return userRedeemthreshold;
}

public void setUserRedeemthreshold(int userRedeemthreshold) {
    this.userRedeemthreshold = userRedeemthreshold;
}
}

如何度过难关?我已经尝试了我知道的方法,但我无法让它工作。

Firebase API 是 asynchronous,这意味着 onDataChange() 方法 returns 在它被调用后立即被调用,并且来自 Task 的回调 returns,稍后会调用。无法保证需要多长时间。因此,在数据可用之前可能需要几百毫秒到几秒。因为那个方法 returns 立即,你试图在 onDataChange() 方法之外使用它的 fetcheduserdata 变量的值,还没有从回调中分配。

基本上,您正在尝试从异步的 API 中同步使用一个值。那不是一个好主意。您应该按预期异步处理 APIs。

快速解决此问题的方法是在您吐司该消息后立即将以下行移动到 onDataChange() 方法中:

userPoints.setText(String.valueOf(fetcheduserdata.getUserPoints()));
userAdrequests.setText(fetcheduserdata.getUserAdrequests());
userClicks.setText(fetcheduserdata.getUserClicks());
userRedeemthreshold.setText(fetcheduserdata.getUserPoints());

否则,我建议您从这个 in which I have explained how it can be done using a custom callback. You can also take a look at this video 中查看我的答案的最后一部分,以便更好地理解。

请注意,不需要创建新的 usageData 对象来取回数据,您可以简单地使用:

userPoints.setText(String.valueOf(up));