My database:
enter image description here
I got "Code". I try to get "ClassID" (Ex: Code=1235, I want a String ClassID= "12"):
Here my code:
private void checkCode(){
String userCode = inputCode.getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Assignment");
Query checkCode = reference.orderByChild("Code").equalTo(userCode);
checkCode.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String classID; // I think here
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
How to do that?
If you want to search the database for all objects that have the "Code" property set to "1235" and then get the value of "classID", please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference assignmentRef = rootRef.child("Assignment");
Query codeQuery = assignmentRef.orderByChild("Code").equalTo("1235");
codeQuery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String classID = ds.child("classID").getValue(String.class);
Log.d("TAG", "ClassID: " + classID);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
ClassID: 12
The exact value you are looking for. Remember that each time you query the database, you need to loop through the results using .getChildren() method, in order to get the results.
Related
on this link is a screenshot of my Firebase Realtime Database structure, instead of getting the Boolean values I want to get the fields that are holding the Boolean values, I have created a model for that to get the data from the database structure,
this is the error am getting
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Boolean to type com.stys.kneckenyapastpapers.model.course_followers
here's the code
mDatabase = FirebaseDatabase.getInstance().getReference("Followers").child("Course").child("AGRI");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot di : snapshot.getChildren()) {
course_followers course_followers = di.getValue(course_followers.class);
follower.add(course_followers);
if (dataSnapshot.child(user.getId()).exists()) {
mUSer.add(user);
}
}
}
Toast.makeText(getContext(), String.valueOf(follower.size()), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
There is no need to create any class when only want to read only some keys in the Realtime Database. Classes are required only when you want to map a node into an object of a particular class. This means that the fields inside the class should be exactly the same as the ones in the database. So it's not your case because those UIDs are dynamically added. To read those keys, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference agriRef = db.child("Followers").child("Course").child("AGRI");
agriRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String uid = ds.getKey();
mUSer.add(uid);
Log.d("TAG", uid);
}
Toast.makeText(getContext(), String.valueOf(mUSer.size()), Toast.LENGTH_SHORT).show();
//It should toast the size of mUSer list.
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
This line is culprit
course_followers course_followers = di.getValue(course_followers.class);
You should try this instead
Boolean course_followers = Boolean.parseBoolean(di.getValue().toString());
The following file explains better what I really mean. It's a screenshot of data sent from a dummy user in Firebase:
The code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
// ref.addValueEventListener(new ValueEventListener() {
ref.orderByChild("Email").equalTo("testing3#testing.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = dataSnapshot.child("Name").getValue().toString();
String state = dataSnapshot.child("State").getValue().toString();
String stateRegion = dataSnapshot.child("StateRegion").getValue().toString();
String telephone = String.valueOf(dataSnapshot.child("Telephone").getValue());
nameEditText.setText(name);
stateEditText.setText(state);
stateRegionEditText.setText(stateRegion);
telephoneEditText.setText(telephone);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Please, can some person help?
More information about data stored in the Firebase:
Because I cannot see a more detailed database schema of yours, I assume that all those user objects are direct children under your Users node, and also assuming that you want to find the user that has the Email set to testing3#tesing.com, to display his particular details, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryUsersByEmail = usersRef.orderByChild("Email").equalTo("testing3#testing.com");
queryUsersByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("Name").getValue(String.class);
Log.d("TAG", name);
String state = ds.child("State").getValue(String.class);
Log.d("TAG", state);
String stateRegion = ds.child("State Region").getValue(String.class);
Log.d("TAG", stateRegion);
String telephone = ds.child("Telephone").getValue(String.class);
Log.d("TAG", telephone);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Paul SMith
Rio de Janeiro
Rio de Janeiro
(00)00000-0000
I am getting all quantity price. But I don't know how to add them all and get it under one string. Can someone pls help
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = mFirebaseDatabase.getReference().child("cart").child(uid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("dasdasdasdad", String.valueOf(dataSnapshot));
String quantityprice = (String) dataSnapshot.child("quantityprice").getValue();
Log.d("quantityprice", String.valueOf(quantityprice));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
In here i am getting all quantityprice value in Log
i.e:- 130,55,150
But i dont know how to add them all and get it under one string.
Anyhelp would be appreciated.
I have tried this too
DatabaseReference databaseReference = mFirebaseDatabase.getReference().child("cart").child(uid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("dasdasdasdad", String.valueOf(dataSnapshot));
Integer total = 0;
String quantityprice = (String) dataSnapshot.child("quantityprice").getValue();
Log.d("quantityprice", String.valueOf(quantityprice));
int price = Integer.valueOf(quantityprice);
total =+ price;
Log.d("total",total); }
but total is shown different all time.
This is Log
D/quantityprice: 130
D/total: 130
D/quantityprice: 55
D/total: 55
D/quantityprice: 150
D/total: 150
To solve this problem, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = db.child("card").child(uid);
productsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
double total = 0.00;
for (DataSnapshot ds : task.getResult().getChildren()) {
String quantityPrice = ds.child("quantityprice").getValue(String.class);
total += Double.parseDouble(quantityPrice);
}
Log.d("TAG", "total: " + total);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
total: 335.00
The key to solving this problem is to parse the String value from the database to a double. Remember, if you need numbers, it's best to store them in the database as numbers and not as String values.
I have written the following code for searching the specific node and it does work correctly.
private void SearchFirebase() {
Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot product : snapshot.getChildren()){
id = product.getKey(); //returns the id(for eg. 8006)
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
But I don't know how to access the child key-value pairs once the specific parent key is known
In the picture above I need to fetch the key-value pairs such as Product Name or Product Discount etc.
You just have to add child to your reference and get data as explained in this answer
private void SearchFirebase() {
Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot product : snapshot.getChildren()){
id = product.getKey();
Log.i(TAG, Rootref.child(id).child("Product Discount").getValue(String.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
When querying a Firebase Realtime Database, the most convenient way for getting the data out is by calling the right child directly from "DataSnapshot" object and converting it to the right type, as explained in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
Query imgUrlQuery = productsRef.orderByChild("IMG").equalTo(imUrl);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String productDiscount = ds.child("Product Discount").getValue(String.class);
String productId = ds.child("Product Id").getValue(String.class);
String productName = ds.child("Product Name").getValue(String.class);
String productPrice = ds.child("Product Price").getValue(String.class);
String shopName = ds.child("Shop Name").getValue(String.class);
Log.d("TAG", productDiscount + "/" + productId + "/" + productName + "/" + productPrice + "/" + shopName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
imgUrlQuery.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
0/8006/Frooti/50/shop-A
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);