I am trying to find the uid from firebase. Let's say I have 3 users in my database, and I want to find the 3rd user uid.
Here is json formate witch is just export from firebase:
{
"-KVKrXu70Ziw0iRw46l5" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkVy5OojpsSUEI24" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkzXy9duyiZq5bM0" : {
"age" : 21,
"emailId" : "ameerhamzaaaa",
"name" : "hamza"
},
"-KVKrl5Ax7ptodMYywzg" : {
"age" : 22,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrr7E6b4-3x6tuwOX" : {
"age" : 23,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKruES01regClm6tWW" : {
"age" : 24,
"emailId" : "ameerhamza",
"name" : "hamza"
}
}
Here is code what I done. But it is not working for me.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.child(newRef.getKey()).setValue(s);
final Query queryRef = myRef.orderByChild("emailId").equalTo("ameerhamzaaaa");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Firebase UID ",dataSnapshot.getKey());//it always null
Student s = dataSnapshot.getValue(Student.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You're creating an extra child and you're searching within the parent. Try something like this:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.setValue(s);
myRef
.orderByChild("emailId")
.equalTo("ameerhamzaaaa")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Student> data = dataSnapshot.getValue(new GenericTypeIndicator<Map<String, Student>>() {});
Map.Entry<String, Student> entry = data.entrySet().iterator().next();
String uid = entry.getKey();
Student s = entry.getValue();
Log.d("Firebase UID ", uid);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// handle error
}
});
It probably doesn't give you the exact id but should give you a better understanding of what's happening.
All Right fox after so much hard work, finaly i get my ANS , Here is how i get the UID from firebase, i use the Firebase Recyler Adapter to get Data From firebase and next you see your self what i done
adapter = new FirebaseRecyclerAdapter<Student, myViewHolader>(
Student.class,R.layout.item_row,myViewHolader.class,myRef
) {
#Override
protected void populateViewHolder(myViewHolader viewHolder, Student model, int position) {
Log.e("myFirebase UID",adapter.getRef(position).getKey());
}
};
recyclerView.setAdapter(adapter);
Related
i have the following json structure:
"Question_Score" : {
"anna_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "anna_01",
"score" : "20",
"user" : "anna"
},
"anna_03" : {
"categoryID" : "03",
"categoryName" : "Constitution",
"question_Score" : "anna_03",
"score" : "170",
"user" : "anna"
},
"stelios_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "stelios_01",
"score" : "230",
"user" : "stelios"
},
"stelios_02" : {
"categoryID" : "02",
"categoryName" : "Widsom",
"question_Score" : "stelios_02",
"score" : "220",
"user" : "stelios"
},
I want for currentuser get the categoryID and score. So probably i need to check equality currentuser == user and then get the categoryID and score for this user. As i m new in firebase i find it a little difficult.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Question_Score");
// Attach a listener to read the data at your profile reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Profile profile = dataSnapshot.getValue(Question_Score.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.v("The read failed: " + databaseError.getCode());
}
});
I dont know from here how to take the values of CategoryId and score to check equality. I ll apriciate any help!
If I understand you correctly you're trying to read the Question_Score child nodes that have a specific value for categoryID. You can do that with a Firebase Database query on the categoryID property:
database = FirebaseDatabase.getInstance();
questionScoreRef = database.getReference("Question_Score");
Query query = questionScoreRef.orderByChild("categoryID").equalTo("01");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, childSnapshot.getKey()+": "+childSnapshot.child("user").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
questionScore.addValueEventListener(postListener);
This prints the key and user value of each child node that has categoryID of "01".
I am trying to retrieve data from firebase. I have successfully established Firebase database but during retrieve operation the getter methods are returns a null value, how to retrieve that information?Object is not null but the getters are returning null.
public class ViewDatabase extends AppCompatActivity {
public FirebaseDatabase firebaseDatabase;
public DatabaseReference databaseReference;
public ListView listView;
public static final String TAG="ViewDatabase";
//Oncreate
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_database);
listView=findViewById(R.id.list);
firebaseDatabase =FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference();
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
//Retriving data
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> array = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User user = ds.getValue(User.class);
if (user != null) {
Log.i(TAG, "user is not null" );
} else {
Log.i(TAG, "user is null" );
}
if(user.getAddress()!=null){
Log.i(TAG, "address is not null" );
}
else{
Log.i(TAG, "address is null" );
}
array = new ArrayList<String>();
array.add(user.getAddress());
array.add(user.getDate());
array.add(user.getEmail());
array.add(user.getFname());
array.add(user.getGender());
array.add(user.getZone());
array.add(user.getLname());
array.add(user.getPhone());
}
ArrayAdapter adapter = new ArrayAdapter(this, layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
}
what am i doing wrong?
//JSON EXPORT
{"User" : {
"-LIN7aCLwUo7fdjSm5ij" : {
"address" : "jagraon",
"date" : "2018/7/27",
"email" : "gurjaps00#gmail.com",
"fname" : "Gurjap",
"id" : "-LIN7aCLwUo7fdjSm5ij",
"lname" : "Singh",
"phone" : "8727050501",
"zone" : "CARDIO ZONE"
},
"-LIN7iFVzA8eVShCSmwu" : {
"address" : "jagraon",
"date" : "2018/7/25",
"email" : "livtaran#gmail.com",
"fname" : "Gurlivtaran",
"id" : "-LIN7iFVzA8eVShCSmwu",
"lname" : "Singh",
"phone" : "8725000740",
"zone" : "STRENTH ZONE"
},
"-LIjA7Kox5dtN8jg9ywY" : {
"address" : "chuuu",
"date" : "Select Expiry Date",
"email" : "cbjj#tuj.dhhu",
"fname" : "dhhxc",
"lname" : "cvhh",
"phone" : "9856533565",
"zone" : "CARDIO ZONE"}
}
}
HERE'S the JSON export done from firebase.
You're reading from the wrong level in your database.
You're reading from the root, and then looping over the children directly under that. That means that you get a snapshot for /User and you're trying to read a User.class from that. That won't work, since there are no properties address, name, etc directly under /User. Those properties live one level lower in your JSON, so your code will need to loop over the individual users too.
One simple fix:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> array = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getKey());
for (DataSnapshot userSnapshot : ds.getChildren()) {
System.out.println(userSnapshot.getKey());
User user = userSnapshot.getValue(User.class);
...
An alternative (and possibly better solution) might be to only read the /User node:
firebaseDatabase =FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference();
databaseReference.child("User").addValueEventListener(new ValueEventListener() {
...
I have a structure in the firebase with some keys, I would like to know how to update a field of the last key generated.
I need to retrieve the last key generated and update the data, how to do that ???
In Json format
What I would like to change "Status"
"-Kuxu1dX_aMcKZbqpGiQ" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h17",
"funcionario" : "João Cardoso",
"motivo" : "Carta",
"nome" : "Felipe Antunes",
"tempo" : -1506424666540,
"visita" : "null"
},
"-KuxuQuZzcTV5T-PHw18" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h19",
"funcionario" : "João Cardoso",
"motivo" : "Encomenda",
"nome" : "Felipe Antunes",
"tempo" : -1506424770025,
"visita" : "null"
}
To be able to make a change to an item, you'll first need to find that item with a query:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("7VCZ8oJSz...");
Query query = ref.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
childSnapshot.getRef().getChild("Status").setValue("New value");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Query:onCancelled", databaseError.toException());
}
});
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("7VCZ8oJSz...");
Query query = yourRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("Status").child("status").setValue("yourNewValue");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("words");
Query word = ref.orderByChild("lang1").equalTo("home");
word.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Word w = singleSnapshot.getValue(Word.class);
Log.i(String.valueOf(R.string.app_name), new Gson().toJson(w));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.e(TAG, "onCancelled", databaseError.toException());
}
});
Could you tell me what am I doing wrong? Here I am, trying to get some "Words" from DB & send Json to Console...
UPD: Imported JSON file
{
"words" : {
"1" : {
"id" : 1,
"lang1" : "s1",
"lang2" : "d1",
"type" : "a"
} ,
"2" : {
"id" : 2,
"lang1" : "s2",
"lang2" : "d2",
"type" : "a"
} // ...
}
}
"sicknessEntries" : [ null, {
"daysSick" : 1,
"sickness" : "Flu",
"type" : "Viral",
"userId" : "K9lPzGCb1AUdNqNywurwNueunv42"
},
-K9lP-zGCb1AUdNqNywurwN {
"daysSick" : 2,
"sickness" : "Pneumonia",
"type" : "Bacterial",
"userId" : "abcd"
},
-NywurwNueunv42 {
"daysSick" : 1,
"severity" : "Medium",
"sickness" : "Shingles",
"type" : "Viral",
"userId" : "user123"
},
{
"daysSick" : 1,
"severity" : "Medium",
"sickness" : "Flu",
"type" : "Viral",
"userId" : "K9lPzGCb1AUdNqNywurwNueunv42"
} ]
For the above json it shows different type of child i have to retrieve only value of the key "sickness" whether it is in the direct child or in the sub child?
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendSnapshot: dataSnapshot.getChildren()) {
System.out.println(friendSnapshot.child("sickness").getValue());
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
If i use the above code it can get only the main child values for the key "sickness" (i.e. it returns the both Flu, Flu only not the others). But i have to get all the sub child values too which have the same key. How to retrieve it?
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refUsers = database.getReference("/childname");
refUsers.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
try {
Iterable<DataSnapshot> children = dataSnapshot.child("sicknessEntries").getChildren();
List<SickModel> sickList = new ArrayList<>();
for (DataSnapshot child : children) {
SickModel sickmodel = child.getValue(SickModel.class);
sickList.add(sickmodel);
}
Try the above code snippet,for retrieving array of sickmodel.
Where sickmodel has daysSick ,sickness,type,userId