I need to get the string value from the node passcode in my Firebase database to compare with a user input, but unfortunately I am not able to get the value. This is the link to my firebase database in the below image.
This is my codes below:
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("pin_code");
mDatabase.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
if (rface.equals("") || rface.equals(null)){
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
Pin pin = new Pin(authUserId, userPassword);
mDatabase.child(userId).setValue(pin);
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
Toast.makeText(PinActivity.this,"Invalid PIN code", Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is the json code
{
"pin_code" : {
"id" : "TQYTo1NHNnhPJnOxhe1Vok3U6ic2",
"pincode" : "12345"
}
}
This FirebaseDatabase.getInstance().getReference("pin_code") does not refer to the node you're looking for. Most likely you know the id property, in which case you can get the node with:
DatabaseReference collection = FirebaseDatabase.getInstance().getReference("p...");
Query query = collection.orderByChild("id").equalTo("TQT...ic2");
query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String rface = (String) child.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
The changes I made:
On the first line we get the collection: the node under which you want to run a query. You struck out the name of that node in the screenshot, but it's the second line you marked.
In the second line we create a query on the id property of each child node under the collection.
In the onDataChange we added a loop. This is needed because a query against the Firebase Database will potentially have multiple results. So the dataSnapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. We loop over dataSnapshot.getChildren() to handle those multiple results.
If there can ever only be one node with the same id, you should consider changing your data structure to use the id as the key of the node. So:
pin_codes
uid1: "pincode1"
uid2: "pincode2"
Your code then becomes significantly simpler, because you don't need to query for the user anymore. You can just directly read from the path:
DatabaseReference user = FirebaseDatabase.getInstance().getReference("pin_codes").child("TQT...ic2");
user.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Try change this:
String rface = (String) dataSnapshot.child("pincode").getValue();
To this:
String rface = (String) dataSnapshot.child("pincode").getValue(String.class);
Use the following::
Object some = dataSnapshot.getValue();
String value = some.toString();
Related
I'm trying to develop a simple application to learn firebase database.
Here is my realtime database schema
mydirectory
-contact_list
-LOyDhepB_IZlM6lZtko
mobileNumber: "9385746982"
name: "Jay"
-LOyDhetiPHalLhXrOaU
mobileNumber: "8000478912"
name: "Ravi"
-LOyDhetiPHalLhXrOaV
mobileNumber: "123456789"
name: "ABC"
-LOyDheubruATyyBp8dG
mobileNumber: "023456879"
name: "XYZ"
I want to get the list of data ordered by name
So I'm using this snippet to load the data in my android application
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("contact_list").orderByChild("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> objectMap = (HashMap<String, Object>) dataSnapshot.getValue();
Master.personList.clear();
for (Object obj : objectMap.values()) {
if (obj instanceof Map) {
Map<String, Object> mapObj = (Map<String, Object>) obj;
String name = (String) mapObj.get("name");
String mobileNumber = (String) mapObj.get("mobileNumber");
Person person = new Person(name, mobileNumber);
Master.personList.add(person);
populateListView();
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("ANDs", "Failed to read value.", error.toException());
}
});
But it does not sort data based on the alphabetical order of name
key. Am I doing anything wrong or missing something?
P.S.
I've also indexing rules (ref), but still result is same! It doesn't sort data alphabetical wise.
{
"rules": {
"mydirectory": {
"contact_list": {
"$user_id": {
".indexOn": ["name"]
}
}
},
".read": true,
".write": true
}
}
I've tried many things from other posts like this topic but nothing works! Please don't make it duplicate instead please help me to solve it!
A HashMap can only contain a key and a value. And the keys in a Map are by definition not ordered. So when you call dataSnapshot.getValue(), you're throwing away all ordering information.
To maintain the order, you'll need to loop over dataSnapshot.getChildren():
public void onDataChange(DataSnapshot dataSnapshot) {
Master.personList.clear();
for (DataSnapshot contactSnapshot: dataSnapshot.getChildren()) {
String name = contactSnapshot.child("name").getValue(String.class);
String mobileNumber = contactSnapshot.child("mobileNumber").getValue(String.class);
Person person = new Person(name, mobileNumber);
Master.personList.add(person);
}
populateListView();
}
You'll also notice that I use child(...) to get a child snapshot for a specific property and get the String value from it. Your approach for that would work too, but I find that I get better error messages when I stick to a snapshot longer (instead of converting to a Map).
String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);
databaseRef
.orderByChild("charID")
.equalTo(selectedCharacter.getCharID())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Translate the character to a map of its data
Map<String,Object> updates = editedCharacter.toMap();
// Update ONLY the node with charID = editedCharacter.getCharID()
databaseRef.updateChildren(updates);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
So I'm trying to update a character's stats in my firebase database. As you can see:
here
the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So your code will need to handle the fact that the snapshot is a list. In the case of Android that means that you loop over snapshot.getChildren():
databaseRef
.orderByChild("charID")
.equalTo(selectedCharacter.getCharID())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
// Translate the character to a map of its data
Map<String,Object> updates = editedCharacter.toMap();
// Update ONLY the node with charID = editedCharacter.getCharID()
child.getRef().updateChildren(updates);
}
}
Instead of databaseRef.updateChildren(updates);
Could you try
databaseRef.child(dataSnapshot.getKey()).setValue(updates)
Then see if it works.
I have database structure like this in Firebase
I want to search a search on this structure based on key number and get the parent key in return. Meaning if i search for 8860124421 then i should get -KTEtSR7chN8te1WaW-W in return .
I am doing it like this in android -
final String number = "8860124421";
DatabaseReference global_user_entry_ref = ApplicationContext.getGlobalDataBaseReference()
.child("User-Entry-2").getRef(); //Reference to User-Entry-2
Query query = global_user_entry_ref.orderByChild("number").equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
for(DataSnapshot friend: dataSnapshot.getChildren()){
String firebase_id = (String) friend.getKey();
Log.d("ContactSync","handle number "+firebase_id+" "+number+" "+friend);
}
Log.d("ContactSync","handle number outer "+dataSnapshot);
//user exist
}
else {
//user_does_not_exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("ContactSync","handle number oncancel "+databaseError.getMessage());
}
});
But I am not getting proper result , dataSanpshot in onDataChange looks like this -
DataSnapshot { key = User-Entry-2, value = null }
but i want to get dataSnapShot with parent of number key.
Please help , Thanks in advance
As #Frank van Puffelen stated in comments , the problem was that i was comparing a number from code with a string in the database , which does not match , Therefore the solution is to change
final String number = "8860124421";
to
final long number = 8860124421;
I have data structure as:
https://law-apps-44h221543638e.firebaseio.com/apps to promote/0/ >> name:"First App", package:"fra"
https://law-apps-44h221543638e.firebaseio.com/apps to promote/1/ >> name:"Second App", package:"sca"
https://law-apps-44h221543638e.firebaseio.com/apps to promote/2/ >> name:"Third App", package:"tha"
and I query it using
Firebase myFirebaseReference = new Firebase("https://law-apps-44h221543638e.firebaseio.com/apps to promote");
Query queryRef = myFirebaseReference.orderByChild("name");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() { // override methods })
But it returns the data in the same order i.e sorted by the first child (1,2,3, etc.)
How should I query it so it sorts the data by the "name" tag of each child?
Ok so I found the answer to this question and I am writing it so others may benefit from it. I was using an older technique wherein I was finding from datasnapshot my apps using their parents' numbers and due to this, I was delibrately undoing the ordering.
Now I have used dataSnapshot.getChildren().iterator() and it is now working correctly. Here's the code:
Query queryRef = myFirebaseReference.orderByChild("name");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name;
String my_package;
long lengthOfForLoop = dataSnapshot.getChildrenCount();
Iterator<DataSnapshot> child = dataSnapshot.getChildren().iterator();
for (int i = 0; i < lengthOfForLoop; i++) {
DataSnapshot next = child.next();
name = next.child("name").getValue(String.class);
my_package = next.child("package").getValue(String.class);
// do something with this data.
}
}
});
}
thanks, Usman!
I used the same code with the children iterable collection in a for loop.
This code was worked for me (in Kotlin):
accountsReference.child(accountId).child("actions").orderByChild("actionPosition").addListenerForSingleValueEvent( object : ValueEventListener {
override fun onDataChange(var1: DataSnapshot) {
if (var1.children != null) {
for (actionsEntries in var1.children) {
...
}
}
Instead of setting the data to null from the child of table Driver.. I want that specific child to be removed.
Here is my sample code.
driverRef = new Firebase(Config.FIREBASE_URL_DRIVER);
Query pendingBus = driverRef.orderByChild("busNum").equalTo(busNum);
pendingBus.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String busnumber = snapshot.child("busNum").getValue().toString();
String empID = snapshot.child("empId").getValue().toString();
if (busnumber.equals(busNum)) {
snapshot.getRef().child("age").setValue("");
snapshot.getRef().child("busNum").setValue("");
snapshot.getRef().child("driversName").setValue("");
snapshot.getRef().child("empId").setValue("");
snapshot.getRef().child("latitude").setValue("");
snapshot.getRef().child("longitude").setValue("");
snapshot.getRef().child("password").setValue("");
snapshot.getRef().child("username").setValue("");
}
}
and this is the output of that method setValue
Instead of using setValue to null
I use .removeValue
Example: snapshot.getRef().child("age").removeValue();
this is worked for me
databaseReference = databaseReference.child("Users").child(mobile);
databaseReference.setValue(null);