def*_*123 1 android firebase firebase-realtime-database
我正在开发一个具有动态视图数量的活动的应用程序。我遇到的问题是我不知道如何在 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
在注释掉的代码段中,我试图生成一组与大小直接相关的视图 .child("sortedCart")
我找不到数据库的子节点的.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) {
}});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
773 次 |
| 最近记录: |