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

时间:2018-08-17 14:26:56

标签: android firebase firebase-realtime-database settext

我有一个带有4张卡片视图的网格布局,并且我在firebase数据库中有要显示在卡片中的数据。从Firebase检索的数据存储在一个类中。关键是我无法使用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>

这是类UsageData:

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;
}
}

如何解决这个问题?我已经尝试了我所知道的方法,但是无法正常工作。

1 个答案:

答案 0 :(得分:0)

Firebase API是func main() { ss := []string{"{1}", "{2}", "{-123}", "{foo}", "{10", "20}", "30"} for _, s := range ss { x, err := parseBraceNumber(s) fmt.Printf("s=%-10qx=%-10derr=%v\n", s, x, err) } // s="{1}" x=1 err=<nil> // s="{2}" x=2 err=<nil> // s="{-123}" x=-123 err=<nil> // s="{foo}" x=0 err=invalid brace number "{foo}" // s="{10" x=0 err=invalid brace number "{10" // s="20}" x=0 err=invalid brace number "20}" // s="30" x=0 err=invalid brace number "30" } func parseBraceNumber(s string) (int64, error) { if len(s) < 3 || s[0] != '{' || s[len(s)-1] != '}' { return 0, fmt.Errorf("invalid brace number %q", s) } x, err := strconv.ParseInt(s[1:len(s)-1], 10, 64) if err != nil { return 0, fmt.Errorf("invalid brace number %q", s) } return x, nil } ,这意味着asynchronous方法在被调用后立即返回,而它返回的onDataChange()的回调将在一段时间后被调用。无法保证需要多长时间。因此,可能需要几百毫秒到几秒钟的时间才能获得该数据。由于该方法会立即返回,因此您尚未尝试从Task方法之外使用它的fetcheduserdata变量的值。

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

对此问题的快速解决方案是在敬酒该消息后立即在onDataChange()方法内移动以下行:

onDataChange()

否则,我建议您从此 strconv.ParseInt(...) 中查看anwser的最后一部分,其中我已经解释了如何使用自定义回调来完成。您也可以查看此 post 以获得更好的理解。

请注意,无需创建userPoints.setText(String.valueOf(fetcheduserdata.getUserPoints())); userAdrequests.setText(fetcheduserdata.getUserAdrequests()); userClicks.setText(fetcheduserdata.getUserClicks()); userRedeemthreshold.setText(fetcheduserdata.getUserPoints()); 的新对象来取回数据,只需使用:

usageData