【问题标题】:How do I auto increment and make index id for a tree in firebase database?如何自动递增并为 firebase 数据库中的树创建索引 ID?
【发布时间】:2021-09-20 09:20:04
【问题描述】:

这是我写的代码,但它不起作用。

    EditText plant = (EditText)findViewById(R.id.plantname);
    String pn = plant.getText().toString();

    FirebaseAuth mAuth;
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();




    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myref  = database.getReference("Plants").child(String.valueOf(id+1));



    myref.child("Name").setValue(pn);
    myref.child("Latitude").setValue(lats);
    myref.child("Longitude").setValue(longs);

我想多次添加这三个细节,但索引不同。

    myref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()){
                id = snapshot.getChildrenCount();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

【问题讨论】:

  • “它不工作”没有提供足够的信息,所以我们可以提供帮助。这段代码中究竟有什么不能按您期望的方式工作?除此之外,停止忽略错误。使用Log.d(TAG, error.getMessage());。您是否在 logcat 中打印了一些内容?
  • FirebaseDatabase 数据库 = FirebaseDatabase.getInstance(); myref = database.getReference("Plants").child(String.valueOf(id+1));在这一行中,索引不会自动增加。
  • 自从 Firebase recommends against this practice 之后你为什么要这样做?
  • 我不知道。除了使用 UID 之外,您能否为我推荐任何其他解决方案。
  • 尝试使用DatabaseReference#push()。这是你想要的吗?

标签: java android firebase indexing auto-increment


【解决方案1】:
 EditText plant = (EditText)findViewById(R.id.plantname);
    String pn = plant.getText().toString();

    FirebaseAuth mAuth;
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();




    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myref  = database.getReference("Plants");



    myref.child(System.currentTimeMillis()).child("Name").setValue(pn);
    myref.child(System.currentTimeMillis()).child("Latitude").setValue(lats);
    myref.child(System.currentTimeMillis()).child("Longitude").setValue(longs);

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 2023-03-26
    • 1970-01-01
    • 2021-05-14
    • 2021-07-22
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    相关资源
    最近更新 更多