Firebase覆盖

时间:2017-06-29 07:14:43

标签: android firebase firebase-realtime-database firebase-authentication

这是我的代码。

    set.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            auth = FirebaseAuth.getInstance();
            final FirebaseUser user = auth.getCurrentUser();
            String emails = user.getEmail().toString().trim();
            String titless = mtitle.getText().toString().trim();
            String pricess = mprice.getText().toString();
            String timess = mtime.getText().toString();
            String productss = mproduct.getText().toString();
            String detailss = mdetail.getText().toString();
            String categorys = mspinner.getSelectedItem().toString().trim();

            final ContactsInfo contact = new ContactsInfo(emails,titless,pricess,timess,productss,detailss,categorys);
            mRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                        i = (int) dataSnapshot.child("商品").getChildrenCount();


                }

                @Override
                public void onCancelled(DatabaseError error) {

                }
            });

            mRef.child("商品").child(String.valueOf(i)).setValue(contact);

        }
    });
}}

当我使用此代码写入我的firebase时,它将覆盖number0的数据,之后它将正常工作,我想知道如果我不想覆盖以前的数据我该怎么办。

1 个答案:

答案 0 :(得分:1)

onDataChange功能代码的执行时间晚于setValueonDataChange函数是异步调用的。请尝试以下代码 -

set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                auth = FirebaseAuth.getInstance();
                final FirebaseUser user = auth.getCurrentUser();
                String emails = user.getEmail().toString().trim();
                String titless = mtitle.getText().toString().trim();
                String pricess = mprice.getText().toString();
                String timess = mtime.getText().toString();
                String productss = mproduct.getText().toString();
                String detailss = mdetail.getText().toString();
                String categorys = mspinner.getSelectedItem().toString().trim();

                final ContactsInfo contact = new ContactsInfo(emails, titless, pricess, timess, productss, detailss, categorys);
                mRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    i = (int) dataSnapshot.child("商品").getChildrenCount();
                    mRef.child("商品").child(String.valueOf(i)).setValue(contact);

                }

                @Override
                public void onCancelled(DatabaseError error) {

                }
            });
            }
        });