android - 获取添加到 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());
解决方案
最简单的方法是将调用push()
(同步的,纯粹是客户端的)与调用setValue
(实际上将数据发送到服务器,并且是异步的)分开。
所以:
val ref = mFirebaseDatabase
.getReference("Posts")
.push()
ref.setValue(post)
.addOnCompleteListener(
c -> {
String postID = ref.key
...
推荐阅读
- android - 可以使用
在 RecyclerView 的 ViewHolder 布局内标记? - android - Volley request JSONArray should be recognized if it was empty
- javascript - 增加对象数量而不是在数组中创建新对象
- erlang - 在 Erlang ODBC 中处理 `nvarchar(MAX)` 问题的任何解决方法?
- python - 如何在 CPLEX-PYTHON(不是 docplex)中生成一些可行的解决方案?
- svelte - 初始化前无法访问“variable_name”
- amazon-ec2 - Windows-Server-2016(AWS) 中的 IIS10 无法将 HTTP 请求重定向到 HTTPS
- linux - g++-8 g++-9 -O2 优化的意外行为
- spring-boot - 如何将spring cloud gateway路由到websocket服务?
- aiohttp - 如何在方案中列表的元素之间包含相同的元素(nbr。或符号)?