我正在开发一个应用程序,该应用程序的 Activity 具有动态的观看次数。我遇到的问题是我不知道如何在 Firebase 中获取数组的大小。
这是我的引用代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_order);
parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final DatabaseReference mCartReference = FirebaseDatabase.getInstance().getReference().child(mAuth.getCurrentUser().getUid().toString()).child("cart");
SharedPreferences mPrefs = getSharedPreferences("label", 0);
mString = mPrefs.getString("tabletIdNum", "default_value_if_variable_not_found");
appContext = getApplicationContext();
// generate items from sortedCart into Views
// for(int i = 0; i < mCartReference.child((mString)).child("sortedCart").size(); i++){
// generate number of views here
// }
Button confirmButton = findViewById(R.id.confirmOrderButton);
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ArrayList<String> items = new ArrayList<>();
final int childCount = parentLinearLayout.getChildCount();
for(int i = 0; i < childCount; i++){
System.out.println(parentLinearLayout.getChildAt(i));
if(parentLinearLayout.getChildAt(i).getClass() == LinearLayout.class){
for (int j = 0; j < ((LinearLayout)parentLinearLayout.getChildAt(i)).getChildCount(); j++) {
System.out.println(((LinearLayout) parentLinearLayout.getChildAt(i)).getChildAt(j));
if(((LinearLayout) parentLinearLayout.getChildAt(i)).getChildAt(j).getClass() == CardView.class){
EditText et = (EditText)((RelativeLayout)((CardView)((LinearLayout) parentLinearLayout.getChildAt(i)).getChildAt(j)).getChildAt(0)).getChildAt(1);
items.add(et.getText().toString());
System.out.println(et.getText().toString());
}
}
}
}
mCartReference.child(mString).child("itemCart").setValue(items);
mCartReference.child(mString).child("name").setValue(mString);
mCartReference.child(mString).child("translated").setValue(0);
Intent startIntent = new Intent(ConfirmOrderActivity.this, ConfirmOrderActivity.class);
startActivity(startIntent);
}
});
}
在被注释掉的代码段中,我尝试生成一组与 .child("sortedCart")
的大小直接相关的 View
我找不到数据库子项的 .length
或 .size()
,如果您有任何解决方案来获取数据库的大小,请告诉我数组(子节点个数)
最佳答案
使用值监听器;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbRef= database.getReference();
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap: dataSnapshot.getChildren()) {
Log.e(snap.getKey(),snap.getChildrenCount() + ""); // here it'll get the size
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}});
关于android - 如何在 android firebase 中找到列表的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996390/