In my app, I have used Firebase database and stored userID in a child and set the value of the child as username to get the username of the current user. Now I'm using addValueEventListener to get the username from the database. This is my Firebase structure.
The code is given below.
checkUsername.child("check").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.child(getUserID()).getValue(String.class);
Log.d(TAG, "onDataChange: currentUser = " + currentUser);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
While debugging, String currentUser returns null.
Screenshot of debugged answer.
Since you have added the valueEventListener at the check node, so getting the child again makes no sense (Because the User ID is the key of check node and not a separate child).
Instead try calling dataSnapshot.getChildren(); directly to get the entire list of updated data and iterate through it to get whatever key value you need.
Something like this,
checkUsername.child("check").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
String current value = dataSnapshot.getValue(String.class);
Log.d("TAG", "onDataChange: " + current value);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Another option in this particular use case is to add a ChildEventListener and get the value inside onChildAdded() method.
Related
I am working on Firebase database. How can I retrieve values from database based on email entered by user in text field. Below is my database structure. Kindly help.
Here is my code:
Ref = database.getReference("Registeration");
Ref.orderByChild("UserRegistration/email").equalTo(emailval).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
user_reg user=dataSnapshot.getValue(user_reg.class);
Toast.makeText(getApplicationContext(), user.toString(), Toast.LENGTH_SHORT).show();
}
You have:
Registration
UserRegistration
12
pushid
key:values
email:emailvalue
To retrieve values always you have to go from top to bottom, so you cannot skip any node.
Only orderByChild(..) query can skip one node (which means you use this query if you want to get children that are not direct children)
Try this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Registration").child("UserRegistration").child("12");
ref.orderByChild("email").equalTo(emailenteredbyuser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String email=datas.child("email").getValue().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
As you can see in the above, the reference passes through every node until node 12.
Then you use this orderByChild("email").equalTo(emailenteredbyuser) to get the email entered by the user.
for (DataSnapshot datas : dataSnapshot.getChildren()) this for loop the datas iterates in inside the direct children of 12 which is the pushid that way you do not need to retrieve the pushid to get the values inside of it.
Try this! here I am running for each loop to get each child.
Ref.child("UserRegistration").child("email").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
user_reg user=dataSnapshot.getValue(user_reg.class);
System.out.println(user.email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get particular value using from DataSnapshot.
I am attaching the screenshot here so kindly check and help me to get particular value from Realtime Database.
Actually I am implementing chat application in which I want to get value of user from group_list.
Here is my code.
private void loadTotalGroupList() {
referenceMainUrl = FirebaseDatabase.getInstance().getReferenceFromUrl("https://pure-coda-174710.firebaseio.com");
referenceGroupList = referenceMainUrl.child("group_list");
//Check if child is available or not.
referenceGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e("dataSnapshot"," ==>"+dataSnapshot);
Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue();
Log.e("newPost"," ==>"+newPost);
Log.e("user: ","==>" + newPost.get("user")); // Here I am getting null value
} else {
Log.e("Child not found", " >>>");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and log showing like this. DataSnapshot { key = group_list, value = {First Group={-KtBH9gnTszNxcXjNu9A={message=assaasas, user=sakib}}} }
I have resolved my issue by using addChildEventListener
referenceGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
Log.e("dataSnapshot KEY", " ==>" + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here dataSnapshot.getKey() returns all sub child of it.
You're listening to the location /group_list in your code. That means a a snapshot from that location will contain the following:
/First Group
/-KtBH9gnTszNxcXjNu9A
message = "..."
user = "..."
If you want to get the user value from that location, you'll have to dig into it using each intermediate path:
dataSnapshot.child("First Group").child("-KtBH9gnTszNxcXjNu9A").child("user").getValue()
Or more simply:
dataSnapshot.child("First Group"/-KtBH9gnTszNxcXjNu9A/user").getValue()
You can't skip the middle paths in the snapshot. Alternatively, you may want to listen to a location closer to the value you want:
referenceMainUrl.child("group_list/First Group/-KtBH9gnTszNxcXjNu9A");
This code runs in a loop and gives you values for all the 'user's
DatabaseReference dRef = FirebaseDatabase.getInstance().getReference().child("group_list").child("First_Group");
dRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("user").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am new on firebase and i am facing some troubles.
mDatabase.child(idUsuario).child("fotos").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
idFoto = dataSnapshot.child("fotoId").getValue().toString();
mDatabase.child("fotos/"+idFoto).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
idFotoStorage = dataSnapshot.child("idfoto").getValue().toString();
System.out.println("The foto id is " + idFotoStorage);
First I get idFoto value from one table (This works).
Then I try to make another search using that value, my problem is that idFotoStorage is always null.
Structure of my Firebase Datebase looks like that:
I want to retrieve data from it in such a manner that when I change the value of the "Name" in database it will instantly change in Android Studio. Right now, I use .addChildEventListner method combined with Map<String, String>. Could someone help me ?
Edit: My code:
Firebase markerRef = myFirebaseRef.child("marker");
markerRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
double latitude = Double.parseDouble(map.get("Lat"));
double longitude = Double.parseDouble(map.get("Lon"));
LatLng location = new LatLng(latitude, longitude);
String filename = map.get("Name");
String[] splitString = filename.split(",");
mMap.addMarker(new MarkerOptions()
.position(location)
.title(splitString[0])
.snippet(splitString[1])
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
In your activity create empty HashMap
Hasmap<String, Marker> markers = new Hashmap<>();
Then in onChildAdded
Marker m = mMap.addMarker(new MarkerOptions()
.position(location)
.title(splitString[0])
.snippet(splitString[1])
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
markers.add.put(dataSnapshot.getKey(), m);
And in onChildChanged
Marker m = markers.get(dataSnapshot.getKey());
m.setPosition(newLocation);
//And anything else, that changing
And finally in onChildRemoved
markers.get(dataSnapshot.getKey()).remove();
markers.remove(dataSnapshot.getKey());
Firebase data is retrieved by attaching an asynchronous listener to a FirebaseDatabase reference. The listener is triggered once for the initial state of the data and again anytime the data changes.
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
To add a value event listener, use the addValueEventListener() or addListenerForSingleValueEvent() method. To add a child event listener, use the addChildEventListener() method.
You can use the onDataChange() method to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null.
Example :-
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
Child events are triggered in response to specific operations that happen to the children of a node from an operation such as a new child added through the push() method or a child being updated through the updateChildren() method. Each of these together can be useful for listening to changes to a specific node in a database.
Example :-
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Comment comment = dataSnapshot.getValue(Comment.class);
// ...
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// ...
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
// ...
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Comment movedComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load comments.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(childEventListener);
In some cases you may want a callback to be called once and then immediately removed, such as when initializing a UI element that you don't expect to change. You can use the addListenerForSingleValueEvent() method to simplify this scenario: it triggers once and then does not trigger again.
This is useful for data that only needs to be loaded once and isn't expected to change frequently or require active listening. For instance,
Example:-
final String userId = getUid();
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
I want to retrive the id that generated by firebase when I pushed value to it like next
I want to retrieve "-KGdKiPSODz7JXzlgl9J" this id for that email
I tried by getKey() but it return "users"
and when user get value it return the whole object from the id to profile picture and that won't make me get it as User object in my app
how solve this ?
Firebase users = myFirebaseRef.child("users");
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getKey();
Log.d("User",dataSnapshot.getRef().toString());
Log.d("User",dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("User",firebaseError.getMessage() );
}
});
You can read the key from push() without pushing the values. Later you can create a child with that key and push the values for that key.
// read the index key
String mGroupId = mGroupRef.push().getKey();
....
....
// create a child with index value
mGroupRef.child(mGroupId).setValue(new ChatGroup());
mGroupId contains the key which is used to index the value you're about to save.
UPDATE 1:
it can obtain also by one line
String key = mDatabase.child("posts").push().getKey();
//**************************************************************//
after searching and trying a lot of things i came to 2 ways to do that
.
1. first one to get the key when i upload the post to the server via this function
public void uploadPostToFirebase(Post post) {
DatabaseReference mFirebase = mFirebaseObject
.getReference(Constants.ACTIVE_POSTS_KEY)
.child(post.type);
mFirebase.push().setValue(post);
Log.d("Post Key" , mFirebase.getKey());
}
i used it in my code to get the key after i have already pushed it to node for it in my database
public void getUserKey(String email) {
Query queryRef = databaseRef.child(Constants.USERS_KEY)
.orderByChild(Constants.USERS_EMAIL)
.equalTo(email);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//TODO auto generated
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//TODO auto generated;
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//TODO auto generated;
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//TODO auto generated
}
#Override
public void onCancelled(DatabaseError databaseError) {
//TODO auto generated
}
});
}
When you fire a Firebase query there can potentially be multiple results. So when you ask for the value of a query, Firebase returns a list of items. Even if there is only one matching item, it will be a list of one item.
So you will have to handle this list in your code:
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
}
}
In Java - Android Studio, you can get the unique pushed ID as the item is written to the db...
Per "Firebase's: Save Data on Android": You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.
To get the reference at write time, instead of loading DATA with a single push()...
use push() to create a blank record in the database, return value is the record's reference.
use .getKey() to get the Key for that record.
use .setValue(DATA) to fill in the blank record
here's an example:
FirebaseDatabase fb_db_instance = FirebaseDatabase.getInstance();
DatabaseReference db_ref_Main = fb_db_instance.getReference("string_db_Branch_Name");
hashMap_record = new HashMap<String, String>(); //some random data
hashMap_record.put("key_Item1", "string_Item1");
hashMap_record.put("key_Item2", "string_Item2");
DatabaseReference blankRecordReference = db_ref_Main ;
DatabaseReference db_ref = blankRecordReference.push(); //creates blank record in db
String str_NEW_Records_Key = db_ref.getKey(); //the UniqueID/key you seek
db_ref.setValue( hashMap_record); //sets the record
I solved it to get id you need to use firebase url
String uid = firebaseRef.child("users").push().getKey();
Log.i("uid", uid);
this will give you the key KG.....
For those using TVAC Tutorials(https://www.youtube.com/watch?v=cSMMWOHkP68&list=PLGCjwl1RrtcTXrWuRTa59RyRmQ4OedWrt&index=16)
You can get Key using onClick method as follows:
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = getRef(position).getKey();
}
});
Just add new field to Users like userID, when you create new User add uid and than you can receive it by reading query
I'm doing it like this.
String userID;// in Users
Firebase users = myFirebaseRef.child("users");
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users user= dataSnapshot.getChildren().iterator().next().getValue(Users.class);
Log.d("User",user.getUserID());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("User",firebaseError.getMessage() );
}
});
I had faced this problem and I found the solution,
you can get it using this code:
dataSnapshot.getChildren().iterator().next().getKey()
// Unity, code in C#
{
reference = FirebaseDatabase.DefaultInstance.RootReference;
string s = reference.Push().Key;
reference.Child(s).Child(Username).SetValueAsync(Username);
Debug.Log(s);
}
Another Option to get the unique Post-id from firebase is by getting key (dataSnapshot.getKey()) in #Override method public void onChildAdded and maintaining it locally for example
private void attachDatabaseReadListener() {
if (mTaskEventListener == null) {
mTaskEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Task friendlyMessage = dataSnapshot.getValue(Task.class);
friendlyMessage.setId(dataSnapshot.getKey());
System.out.println("friendlyMessage = " + friendlyMessage);
DummyContent.ITEMS.add(new DummyContent.DummyItem("" + DummyContent.ITEMS.size()+1,friendlyMessage.getStatus(),friendlyMessage.getSummary()));
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mUserDatabaseReference.addChildEventListener(mTaskEventListener); // remove it
}
}
dataSnapshot.getKey will set the unique post id in Task Instance and can be used later to perform any update operation.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference1 = firebaseDatabase.getReference("users");
databaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String key = dataSnapshot1.getKey();
Log.d(TAG, "onCreate: key :" + key);
String email = dataSnapshot1.child("email").getValue(String.class);
String roomno =dataSnapshot1.child("address").getValue(String.class);
Log.d(TAG, "onDataChange: email: " + email);
Log.d(TAG, "onDataChange: address: " + address)
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Use this
mFirebaseDatabase=mFirebaseDatabase.getInstance().getReference("tablename");
Query query = mFirebaseDatabase.orderByChild("tablenme").getRef();
query.orderByChild("Id").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String id =dataSnapshot1.child("Id").getKey();
String Name = dataSnapshot1.child("Name").getValue().toString();
String lastName= dataSnapshot1.child("lastname").getValue().toString();
flatDataGets.add(Name+"-"+lastname);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(RagisterActivity.this, R.layout.support_simple_spinner_dropdown_item, DataGets);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mRegisterSpinner.setAdapter(arrayAdapter);
mRegisterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
flatName =DataGets.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Yes, you can retrieve the node or main child name by adding its name in that particular child as a key and value {main_child_name}.
Simply do similar:
HashMap<String, Object> hashLcl = new HashMap<>();
hashLcl.put("admin", firebaseUser.getUid());
hashLcl.put("name", textPrm);
DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference();
String keyLcl = referenceLcl.child("GroupChats").push().getKey();
hashLcl.put("key", keyLcl);
Task task = referenceLcl.child("GroupChats").child(keyLcl).setValue(hashLcl);
task.addOnSuccessListener(aVoid -> {
//the data is added and now we are sure to do something related
});
This is the result:
String id = Objects.requireNonNull(task.getResult().getUser()).getUid();