【问题标题】:Save multiple data with same uid to Firebase database将具有相同 uid 的多个数据保存到 Firebase 数据库
【发布时间】:2017-04-15 11:17:08
【问题描述】:

我正在 Android Studio 中开发一个使用 Firebase 登录并将数据存储到其实时数据库的应用。 我使用的是默认的 firebase 数据库规则,因此只有经过身份验证的用户才能在数据库中写入/读取。

我有一个活动 (AddMarker),它将两个 editText 值和一个 LatLong 值(这个来自另一个活动)保存到数据库中。 该代码实际上正在运行,我可以通过这种方式查看存储在其中的数据: DB structure

问题是每次我保存(在 AddMarker 活动中)时,链接到该 id 的先前数据都会被新的数据替换。
相反,我想在数据库中存储多个具有相同 id 的值,例如: DB structure 2

这是我的代码

public class AddMarker extends AppCompatActivity implements View.OnClickListener {

    //Save flag
    public static boolean isSaved;

    //Database
    private DatabaseReference databaseReference;
    FirebaseAuth firebaseAuth;
    private FirebaseAuth mAuth;

    //UI
    private EditText tipo, marca;
    private Button saveMarker;

    public LatLng ll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_marker);

        //DB
        mAuth = FirebaseAuth.getInstance();
        databaseReference = FirebaseDatabase.getInstance().getReference();


        //Initialize views
        tipo = (EditText) findViewById(R.id.type);
        marca = (EditText) findViewById(R.id.specInfo);
        saveMarker = (Button) findViewById(R.id.save_btn);

        //Initialize isSaved
        isSaved = false;

        //Set button listener
        saveMarker.setOnClickListener(this);

        //get Position
        ll = getIntent().getParcelableExtra("POSITION");

    }

    private MarkerOptions saveMarkerInfo(){

        String tipo_str = tipo.getText().toString().trim();
        String marca_str = marca.getText().toString().trim();
        LatLng pos = ll;

        MarkerInfo markerInfo = new MarkerInfo(tipo_str,marca_str, pos);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();


        MarkerOptions marker = new MarkerOptions()
                .position(ll)
                .anchor(0.0f, 1.0f)
                .title("prova")

        //Add data to DB
        databaseReference.child(user.getUid()).setValue(markerInfo);


        Toast.makeText(this,"infos saved",Toast.LENGTH_LONG).show();

        finish();

        return marker;
    }

    @Override
    public void onClick(View v) {

        if(v == saveMarker){
            isSaved = true;
            MarkerOptions mo=saveMarkerInfo();

            MainActivity.mMap.addMarker(mo);

        }

    }
}

【问题讨论】:

    标签: android firebase firebase-realtime-database uid


    【解决方案1】:

    您不能创建两个具有相同 ID 的节点,而是可以在每个 userId 内创建一个嵌套结构。并像这样设置值。

     databaseReference.child(user.getUid()).push().setValue(markerInfo);
    

    这将使用您的多个数据在 singleUserId 下创建子项

    了解更多you can refer this

    【讨论】:

    • 谢谢!我通过使用 Push uid 解决了我的问题,但是您的解决方案将在将来对我最终的其他项目有很大帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多