我是android studio的新手。我想知道“塑料”在 Firebase 檔案欄位中出現了多少次。并在 MPChart 中顯示。我在 Firebase Connect 中計算了“Plastic”,但它不能在 data() 中作業。我該如何撰寫 Plastic?
public class MainChart {
BarChart barChart;
int Plastic;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
getMultipleDocs();
BarData barData = new BarData();
barData.addDataSet(barDataSet);
barChart.setData(barData);
barChart.invalidate();
}
public void getMultipleDocs() {
.collection("Garbage")
.whereEqualTo("name","plastic")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> snapshotList = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot snapshot:snapshotList){
Log.d(TAG, "onSuccess: " snapshot.getData().toString());
}
Plastic ;
Log.d(getClass().getName(), "plastic have = " Plastic);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "onFailure: ", e);
}
});
public ArrayList<BarEntry> data(){
ArrayList<BarEntry> dataVal = new ArrayList<>();
dataVal.add(new BarEntry(0,Plastic));
return dataVal;
}
}
我的 getMultipleDocs() 代碼
我的資料()代碼
uj5u.com熱心網友回復:
資料是從 Firestore(和大多數現代云 API)異步加載的,因為這可能需要一些時間。在加載資料時,您的主代碼會繼續執行。然后,當資料可用時,您onSuccess將被呼叫。
這樣做的結果是您dataVal.add(new BarEntry(0,Plastic))之前的運行Plastic 被呼叫。您可以通過在除錯器中運行代碼并設定斷點或使用一些井位日志陳述句來最輕松地驗證這一點。
解決方案始終相同:任何需要 Firestore 資料的代碼都需要在內部onSuccess或從那里呼叫。所以:
...
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> snapshotList = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot snapshot:snapshotList){
Log.d(TAG, "onSuccess: " snapshot.getData().toString());
}
Plastic ;
Log.d(getClass().getName(), "plastic have = " Plastic);
public ArrayList<BarEntry> data(){
ArrayList<BarEntry> dataVal = new ArrayList<>();
dataVal.add(new BarEntry(0,Plastic));
return dataVal;
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "onFailure: ", e);
}
});
有關更多資訊,請參見:
- 如何檢查某個資料是否已經存在于firestore中
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/355667.html
標籤:安卓 火力基地 谷歌云firestore
