一旦保存对象,就可以在Firebase中获取已保存的密钥 [英] Get saved key in Firebase as soon as object is saved
问题描述
我是Firebase的新手,到目前为止,Firebase已经走到了尽头。像保存对象和检索对象。我想知道如何获得保存的对象的关键。在休眠状态下,只要保存一个对象,就会返回键。我想知道如何在Firebase中实现这一点。以下是我的代码,但到目前为止我得到nullpointerexception。
ref.child(Advertisements)。push ).setValue(mobileAdd);
ref.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
StorageReference storageReference = ();
storageReference.putFile(uri);
}
@Override
public void onCancelled(FirebaseError firebaseError){
}); PS:我希望该密钥在Firebase中的存储空间中创建一个文件夹,以便我可以将这些图像保存到创建文件夹。
解决方案 DatabaseReference.push()是一个纯粹的客户端操作返回一个引用到一个新的位置,统计保证是唯一的。所以你可以先运行它,并从中获取密钥,然后根据该密钥创建一个存储引用:
$ b $ pre $ DatabaseReference newDatabaseRef = ref.child( 广告)推送();
StorageReference newStorageRef = mStorageReference.child(advertisement)。child(newRef.getKey())。child(uri.getLastPathSegment());
然后最后将值设置到数据库并将文件存储到存储中:
newDatabaseRef.setValue(mobileAdd);
newStorageRef.putFile(uri);
I'm new to Firebase and I've come so far with Firebase so far. Like saving objects and retrieving object. I want to know how to get the key of the object saved. In hibernate, it returns key whenever it saves an object. I want to know how this can be achieved in Firebase. Following is the my code, but so far I'm getting nullpointerexception.
ref.child("Advertisements").push().setValue(mobileAdd);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
StorageReference storageReference = mStorageReference.child("advertisement").child(dataSnapshot.getKey()).child(uri.getLastPathSegment());
storageReference.putFile(uri);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
PS: I want that key to create a folder in storage in Firebase so I can save those images to that created folder.
解决方案 DatabaseReference.push()
is a pure client-side operation that returns a reference to a new location that is statistically guaranteed to be unique. So you can first run that and get the key from it, then create a storage reference based on that key:
DatabaseReference newDatabaseRef = ref.child("Advertisements").push();
StorageReference newStorageRef = mStorageReference.child("advertisement").child(newRef.getKey()).child(uri.getLastPathSegment());
And then finally set the value to the database and put the file to storage:
newDatabaseRef.setValue(mobileAdd);
newStorageRef.putFile(uri);
这篇关于一旦保存对象,就可以在Firebase中获取已保存的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文