Reputation: 4571
I'm leaning Firebase.
I pushed some data in db like below
-test -LBpjFMIPq-kQWyBmqf7 -str : value-a
but dataSnapshot.getKey() always get repository's name the "test".
How can I get the unique id that push() had made?
unique id is LBpjFMIPq-kQWyBmqf7 in this case.
package com.example.happy.firebasetest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
String key;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref1 = database.getReference("test");
ref1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
key = dataSnapshot.getKey();
System.out.println(key);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
so key
Upvotes: 0
Views: 45
Reputation: 80952
Try the following:
ref1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
key = datas.getKey();
System.out.println(key);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
You need to loop inside the push()
key then use the method getKey()
to retrieve the source location which is the unique id.
Upvotes: 1