Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation
Related
I'm trying to retrieve a specific value from a Firebase realtime Database.
The data looks like this:
I want to get the URL value from any of them and then put it into a string variable to use later. This is so that the program does not need to be changed if the download link is changed. The code I have so far is;
DatabaseReference fdb = FirebaseDatabase.getInstance().getReference();
//Query query = fdb.child("URLDOWNLOADS").child("WSSeasons")
fdb.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot url : dataSnapshot.getChildren())
{
LoginInfoFirebasedb DownURL = url.getValue(LoginInfoFirebasedb.class);
String temp = DownURL.dwldURL;
URL1 = temp;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
Some help would be seriously appreciated. I understand this may be a simple problem but I am stumped.
To get each url as a String, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("URLDOWNLOADS");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String url = ds.child("URL").getValue(String.class);
Log.d(TAG, key + " / " + url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
How can I get a list of all "Floor" elements in my database. If I use the following database my list should have 3 elements. List should contain the elements with the id's 1234, 4321, 2341.
mydatabase
-buildings
--LNBxRoNBhVZyXniqe9t
---checked
---anzI
---anzA
---floors
----f1
-----1234
------description
------id
----f2
-----4321
------description
------id
--LXdsafRfasdf12asdfJ
---checked
---anzI
---anzA
---floors
----f1
-----2341
------description
------id
This is my DAO:
private FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("buildings");
#Override
public void initialize() {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
List<Floors> list = new LinkedList<>();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
????
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}});
You will need to traverse the DataSnapshot that you get from Firebase. Something like this
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot floorSnapshot: buildingSnapshot.child("floors").getChildren()) {
for (DataSnapshot numberSnapshot: floorSnapshot.getChildren()) {
Log.i(TAG, numberSnapshot.getKey()); // "1234", "4321", "2341"
Log.i(TAG, ""+numberSnapshot.child("id").getValue());
}
}
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
How can I get a list of all "Floor" elements in my Database?
In a very simple way, by iterating the database using getChildren() method three times.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference buildingsRef = rootRef.child("buildings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.child("floors").getChildren()) {
for(DataSnapshot d : ds.getChildren()) {
String key = d.getKey();
String description = d.child("description").getValue(String.class);
list.add(key);
Log.d("TAG", key);
}
}
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
};
buildingsRef.addListenerForSingleValueEvent(valueEventListener);
List should contain the elements with the id's 1234, 4321, 2341
The list will contain those exact three ids. If you try to print the list in your logcat, the result will be:
[1234, 4321, 2341]
{
"History" : {
"-LIRZ4Nf2HyTTYtZEeOA" : {
"destination" : "101 Main Street, Your Town, Your Country",
"driver" : "vP9r4F2yDWRRuvKjRiQvMEXVuoK2",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 3.63,
"rider" : "C0RjB5NPZcTvWz9XiUAhpTDOK0C2",
"status" : "accepted",
"timestamp" : 1532709012
}
}
The above is the History node in my Firebase database.
My ultimate goal is to send an alert dialog once the payment response = "approved" but, in this case, when there is more than one key in the History node, the alerts run on top of each other.
What can I do so this does not happen?
The code I am using to get the key for each History entry is:
private void getPaymentResponse() {
final DatabaseReference paymentConfirmed = FirebaseDatabase.getInstance().getReference("History");
paymentConfirmed.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ryydeKey = ds.getKey(); **<-- gets the key**
DatabaseReference response = FirebaseDatabase.getInstance().getReference("History")
.child(ryydeKey);
response.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals("payment response")) {
String response = String.valueOf(child.getValue().toString());
if (response.equals("approved")) {
proceedToPickupDialog();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I am assuming that the code:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ryydeKey = ds.getKey();
is getting all the keys, but all I want is the present key.
Edit
I am putting in this code and nothing is printing up. Tried logs and toasts.
DatabaseReference payRef = FirebaseDatabase.getInstance().getReference();
Query query = payRef.child("History").orderByChild("driver").equalTo(driverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String response = ds.child("payment response").getValue(String.class);
Log.e(TAG, "response = " + response);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
When you are using getChildren() method, it means that you are looping through the entire DataSnapshot object. If the DataSnapshot contains more then one child, then the alerts will run on top of each other. If you want to check only for a particular child, you need to change the code a little bit.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("History").child("-LIRZ4Nf2HyTTYtZEeOA");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String response = dataSnapshot.child("payment response").getValue(String.class);
if(response.equalTo("approved")) {
Log.d("TAG", "Payment approved!");
} else {
Log.d("TAG", "Payment not approved!");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
idRef.addListenerForSingleValueEvent(valueEventListener);
Using this code, you get only the response form a single child. To actually get this work done, first you need to store this value -LIRZ4Nf2HyTTYtZEeOA in a variable in order to be able to use in your reference.
Edit: This another approach using a query"
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("History").orderByChild("driver").equalsTo(driverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String response = dataSnapshot.child("payment response").getValue(String.class);
if(response.equalTo("approved")) {
Log.d("TAG", "Payment approved!");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
I have a database that looks like this:
And my code like this:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uniqueKey:dataSnapshot.getChildren()) {
for (DataSnapshot keysiswa:uniqueKey.getChildren()) {
for (DataSnapshot valuesiswa:keysiswa.child("nama_siswa").getChildren()) {
String c = valuesiswa.getValue().toString();
Log.i(TAG,c);
}
}
}
}
I want to take the value of "nama_siswa" but nothing happens in logcat. What is wrong with my code?
Try this code.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("siswa");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Name:",dataSnapshot.getValue(User.class).name); // define your pojo class
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get the value of nama_siswa property, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference siswaRef = rootRef.child("siswa");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama_siswa = ds.child("nama_siswa").getValue(String.class);
Log.d("TAG", nama_siswa);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
siswaRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
chandra
coba
I want to retrieve "7753400075_Canada_twinpalms_||_twinpalms_20170824001545_F5BA7F33AD51CE283332001BEC409A46" key, How to do so? Here is my code...
ref.addValueEventListener(new ValueEventListener() { //addListenerForSingleValueEvent
#Override
public void onCancelled(DatabaseError arg0) {
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object response = dataSnapshot.getValue();
System.out.println("read data :"+response);
}
});
ref.child("chatmessage").child("devicetoken").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
// Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// System.out.println("previousChildName :"+previousChildName);
}
}
});
Here is the Firebase database example:
I tried using child data snapshot method but did not worked. It returns all data. But i need to get only the new child added parent. Any help for this will be much appreciated.
To solve this, you need to filter your results. Assuming that chatmessage is a direct child of your Firebase database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference deviceTokenRef = rootRef.child("chatmessage").child("devicetoken");
Query query = deviceTokenRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);