[英]How to display data from Firestore in a RecyclerView with Android?
[英]How to display integer from firebase firestore to Android Studio's TextView?
我目前正在做一個項目,在這個項目中,用戶將他們的垃圾分開,作為回報,它給了他們積分。 他們可以使用這些積分兌換獎勵。 目前我無法在 Android Studio 的 TextView 中顯示點數。這是我的代碼。 我的數據庫結構https://imgur.com/wOGfYOg我希望這些點顯示在我的儀表板上的 TextView 上https://imgur.com/zJjSNgO問題出現在 DocumentReference 部分。
public class MainActivity extends AppCompatActivity {
private TextView powents;
FirebaseFirestore fStore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button logout = findViewById(R.id.logout);
ImageView qrimage = findViewById(R.id.qrimage);
powents = findViewById(R.id.powents);
fStore = FirebaseFirestore.getInstance();
DocumentReference docref = fStore.collection("Users").document("Users");
docref.addSnapshotListener(this, (documentSnapshot, error) -> {
powents.setText(Math.toIntExact(documentSnapshot.getLong("Points")));
});
try {
BarcodeEncoder barcode = new BarcodeEncoder();
Bitmap bitmap = barcode.encodeBitmap(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getEmail(), BarcodeFormat.QR_CODE, 650, 650);
qrimage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
logout.setOnClickListener(view -> {
FirebaseAuth.getInstance().signOut();
Toast.makeText(MainActivity.this, "Logged Out!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, Login.class));
finish();
});
}
}
您的代碼中的問題似乎出在這行代碼中:
DocumentReference docref = fStore.collection("Users").document("Users");
當您使用上述參考時,這意味着您正在嘗試閱讀一個名為Users
的文檔,該文檔實際上並不存在,因為您的屏幕截圖顯示文檔 ID 為user1@gmail.com
。 要解決此問題,只需將上述文檔參考更改為:
DocumentReference docref = fStore.collection("Users").document("user1@gmail.com");
只要您有適當的規則,您的代碼就應該如此。 也不要忘記附加一個失敗的偵聽器,以查看是否出現問題。
我認為documentSnapshot.getLong("Points")是 null,這就是你得到 NPE(空指針異常)並且你不能將值設置為 textview 的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.