如何在Firebase中不使用.push()的情况下避免覆盖?使用自动增量生成ID来替换.push() [英] How to avoid the overwriting without using .push() in Firebase? Using the autoincrement to generate ID to replace .push()

查看:36
本文介绍了如何在Firebase中不使用.push()的情况下避免覆盖?使用自动增量生成ID来替换.push()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试生成ID(自动递增)以替换唯一ID.有人可以帮我解决这个问题吗?谢谢!

I try to generate the ID(autoincrement) to replace the unique ID. Could somebody help me to solve this problem? Thank you!

public void SignUp(){

    int UserCount = 1;
    String identifier ="User" + UserCount;
    Firebase userRef = firebaseRef.child("Users");
    EditText nameInput = (EditText) findViewById(R.id.nameTxt);
    String name = nameInput.getText().toString();

    EditText passInput = (EditText) findViewById(R.id.passwordTxt);
    String password = passInput.getText().toString();

    EditText addrInput = (EditText) findViewById(R.id.addressTxt);
    String address = addrInput.getText().toString();
    if (!name.equals("")){
        Map<String, String> infor= new HashMap<String, String>();
        caloocan.put("Usersname", name);
        caloocan.put("Userspassword", password);
        caloocan.put("Usersaddress", address);

        Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
        users.put(identifier,infor);

        userRef.setValue(users);
        UserCount++;
    }
}

由Firebase生成的唯一ID

使用自动增量生成ID,就像在SQL数据库中使用的

推荐答案

如果您确实要避免使用 push()方法,则需要在设置值之前从数据库中检索所有用户.

If you really want to avoid using push() method, then you need to retrieve all users from your database before setting the value.

这是这样做的方法

userRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int count = dataSnapshot.getChildrenCount() + 1;
        String identifier = "User" + count;

        // save the new user
        userRef.setValue( ... );
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

这篇关于如何在Firebase中不使用.push()的情况下避免覆盖?使用自动增量生成ID来替换.push()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆