首页 > 解决方案 > 获取添加到 Firebase 实时数据库的新帖子的 ID

问题描述

我想检索最近发送到 firebase 的帖子的 ID

在此处输入图像描述

例如我想返回 ID MYl69JC9vmx25q4ACWu

我在这


    mFirebaseDatabase
        .getReference("Posts")
        .push()
        .setValue(post)
        .addOnCompleteListener(
            c -> {

               String postID = "" // get post id

              /** After adding a question a user should be taken to ViewQuestion Fragment  
               * pass the postID to the ViewQuestion Fragment


              */
              if (c.isSuccessful()) Toast.makeText(this, postID, Toast.LENGTH_SHORT).show();
              else
                Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT)
                    .show();
            })
        .addOnFailureListener(
            e -> Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show());



标签: androidfirebasefirebase-realtime-database

解决方案


最简单的方法是将调用push()(同步的,纯粹是客户端的)与调用setValue(实际上将数据发送到服务器,并且是异步的)分开。

所以:

val ref = mFirebaseDatabase
    .getReference("Posts")
    .push()

ref.setValue(post)
    .addOnCompleteListener(
        c -> {
           String postID = ref.key
           ...

推荐阅读