I'm developing a reservation mobile app wherein when I click the checkAvailability, it will check if the data already exists in the database. My problem is that I don't know how to access since the key is randomly generated. There is a lot of similar questions to mine but no solutions has been working for me.
Firebase Database(Screenshot):
btnAvailability.setOnClickListener
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String type = dataSnapshot.child("checkIn").getValue().toString();
String type2 = dataSnapshot.child("productName").getValue().toString();
if(type.equals(checkInTV.getText().toString()) && type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
From the looks of it, you're trying to check of there is a child that has order/0 with a specific checkIn and productName under Requests. In your current data structure you can do that with:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type = snapshot.child("checkIn").getValue().toString();
String type2 = snapshot.child("productName").getValue().toString();
if(type.equals("Saturday, April 20, 2019") && type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
Differences from your code:
I have a loop inside onDataChange, since a query can have multiple results.
I hardcoded the date to rule out the problem being caused by the way you input the data in the text view.
I handle onCancelled, since ignoring errors is just a bad idea.
A more efficient way to accomplish the same is to have Firebase do part of the query, like this:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo("Saturday, April 20, 2019");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("productName").getValue().toString();
if(type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
In here the change is:
I moved part of the check into the query, so that Firebase can perform that filter on the server. This means it has to download less data to the client, making it both faster and cheaper.
You'll still have to filter the second value client-side, since Firebase queries can only order/filter on one property. For more on this, see Query based on multiple where clauses in Firebase.
Note that you're querying double nested data. While you can get this to work for a specific order (orders/0 in this example), if you can have multiple orders in a request, Firebase won't be able to query across all of them.
For more on this and a solution, see: Firebase Query Double Nested
I'd also recommend reading my answers about modeling categories, because I have a feeling you'll need this soon: Firebase query if child of child contains a value
While storing data you need make user email id as first parameter so that you can access data based on user.
{"reuest":{"xyz#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]},"abc#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]}}}
Finally found a solution on my problem.
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo(checkInTV.getText().toString());
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("order/0/productName").getValue().toString();
if(type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
});
Related
I know that there is a lot of code on this, but I can't find the solution for my problem.
I have a realtime database :
I have to fetch "saluteBossMassima:"
The way I have declared and initialized my variables:
DatabaseReference databaseMonster;
String id;
databaseMonster=FirebaseDatabase.getInstance().getReference("monster");
id = databaseMonster.push().getKey();
The code that I try:
databaseMonster.child(id).addValueEventListener(newValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String saluteMassimaBossDB = dataSnapshot.child("monster").child("saluteBossMassima").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Anyone can help me?
This won't work:
databaseMonster=FirebaseDatabase.getInstance().getReference("monster");
id = databaseMonster.push().getKey();
When you call push() it generates a new unique key for writing to. There is zero chance that this is the same as the existing key in your screenshot.
If you already know the key of the node you want to read, you should pass that key to child():
// 👇 specify key here
databaseMonster.child("-MtcylP327pK9pUQB54").addValueEventListener(newValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String saluteMassimaBossDB = dataSnapshot.child("saluteBossMassima").getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // 👈 never ignore errors
}
});
If you know some value of the node(s) you want to read, but not the key, you can use a query to find the nodes:
// 👇 Use a query to select the nodes with a specific value
Query query = databaseMonster.orderByChild("dannoAttaccoCaricato").equalTo(300);
query.addValueEventListener(newValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// 👇 Loop over the results, since there may be multiple
for (DataSnapshot monsterSnapshot: dataSnapshot.getChildren()) {
String id = monsterSnapshot.getKey();
String saluteMassimaBossDB = monsterSnapshot.child("saluteBossMassima").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
Now we need to loop over dataSnapshot.getChildren(), since there may be multiple nodes with the value of 300 for dannoAttaccoCaricato.
If you know nothing about the node, the best you can do is read all of them and loop over the results:
// 👇 Read all nodes under /monster
databaseMonster.addValueEventListener(newValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot monsterSnapshot: dataSnapshot.getChildren()) {
String id = monsterSnapshot.getKey();
String saluteMassimaBossDB = monsterSnapshot.child("saluteBossMassima").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
In my android application, when the user logs in, I need to check my realtime database to determine if the users ID exists within this database. Once the users ID has been located, i then need to retrieve the parent node of this ID in order to determine if the user logging in is a customer or employee. I'm having some difficulties coding this, as i'm relatively new to using firebase.
Here is my code so far:
final String user_id = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener eventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for(DataSnapshot ds : dataSnapshot.getChildren())
{
if(ds.child(user_id).exists())
{
//check if employee or customer?
String cust_or_emp = ds.child(user_id).getKey();
Log.d("test1",String.valueOf(ds.child(user_id).getKey()));
if (cust_or_emp.equals("Customers"))
{
name= Objects.requireNonNull(ds.child(user_id).child("User_Information").child("firstName").getValue()).toString();
Log.e("first name is ", "firstname :" + name);
toNextActivity = new Intent(getActivity(), MainActivity.class);
toNextActivity.putExtra("name",name);
Log.e("2first name is ", "firstname :" + name);
progressBarLayout2.setVisibility(View.GONE);
Objects.requireNonNull(getActivity()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Objects.requireNonNull(getActivity()).startActivity(toNextActivity);
getActivity().finish();
} else if (cust_or_emp.equals("Employee")) {
//code for if the key is employee
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
Log.d("error", databaseError.getMessage()); //Don't ignore errors!
}
};
rootRef.addListenerForSingleValueEvent(eventListener);
Currently when I run my application, nothing appears to happen.
You're attaching a value listener to the root of your database. Then in your onDataChange you loop over the child node, which means that your ds snapshot is for the Users node, while you seem to think it's for the Employee and Customers node.
The fix should be to listen to the Users node instead:
rootRef.child("Users").addListenerForSingleValueEvent(eventListener);
Your current approach is highly inefficient, as (even when you fix the above) you're loading the entire Users node to check if a specific user exists in there. As you add more users to the app, this means you're loading more and more data, without using it.
A better approach is to check whether the specific user exists under each specific node:
rootRef.child("Users/Employee").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
... handle the Employee
}
else {
rootRef.child("Users/Customer").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
... handle the Customer
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I need to find the existing Child inside the Random Key and I have used OrderByChild() and EqualTo() to filter the queries but it behaves soo weird that for sometimes it showing child exists for only one Child and for sometimes it doesnot work.
i need to check for the child (date_expense) of "February_2019" exist or not? i've tried this
MainActivity
databaseReference = firebaseDatabase.getReference("Expenses_Details");
expensesaddref = databaseReference.child(username).child("Expense_Month").child(monthyr);
int currentInt=Integer.parseInt(currentdate);
numberToWord((currentInt % 100));
Log.d("date_string",String.valueOf(dateString));
final String date_expense=expensesname +"" + dateString;
final ExpenseClass expenses=new ExpenseClass(expensesname,currentdate,date_expense,totalcost);
expensesaddref.orderByChild("date_expense").equalTo(date_expense).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getContext(), "Expense Already exists!!", Toast.LENGTH_SHORT).show();
}
else {
String key = expensesaddref.push().getKey();
expensesaddref.child(key).setValue(expenses);
showListAdd(expensesname);
Log.d("Adding", "Data Adding");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}}
Note
if child exist already in db then it should display toast but expense is again adding even though the child is already db
In the Program,
monthYr is February_2019
Currentdate is date of the present day
dateString is date in words(ie one,Eleven,Twenty)
This is the Firebase structure what Iam getting .date_expense is adding even though child is exist already
i have found that the below code working as per my need
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
boolean isTitleAlreadyUsed = false;
for (DataSnapshot ds: dataSnapshot.getChildren()) {
if (ds.hasChild("date_expense") && (expDate.equals(ds.child("date_expense").getValue()))) {
isTitleAlreadyUsed = true;
}
}
if(isTitleAlreadyUsed){
Toast.makeText(getContext(),"Exist",Toast.LENGTH_SHORT).show();
}else
{
String key=expensesaddref.push().getKey();
expensesaddref.child(key).setValue(expenseClass);
showListAdd(lower_exp);
Toast.makeText(getContext(),"Added",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
expensesaddref.addListenerForSingleValueEvent(valueEventListener);
I'm trying to make an app in which user store his Data. I've used user shared preferences to save user login details but still for security purpose, i made an activity(Verify Passcode Activity) that ask user Passcode to allow access on the data. Now i'm able to save, fetch and delete data. But in my Verify Passcode Activity, i just want to fetch that particular key and value where passcode is stored. I don't want to fetch complete data in Verify Passcode Activity.
Below is the code which i used to save passcode to database:-
databaseReference.child(uniqueID).setValue(passcode);
Below is the code i'm tried to fetch only passcode:-
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here uniqueID is "abhishek88666kumar"and pass is a variable used for getText().
Here is the screenshot of my Firebase Database :-
Database Screenshot
Here is Verify Passcode Activity Screenshot:-
Please have a look at Database Screenshot and Verify Passcode Activity Screenshot.
Agenda:
getText() from textView inside activity.
getValue from firebase realtime database (only for current user. 'abhishek88666kumar' in our case).
compare if 1 and 2 are same or not. (If same then redirect to MainActivity else show error.)
Please tell me what i'm doing wrong.
Thanks to all for your help :) Your answer didn't worked for me but with the help of your answers and my few knowledge, I made a solution for my problem myself.
Here is the code that matches my requirement. This code is working exactly how I wanted.
dbreference = FirebaseDatabase.getInstance().getReference("passcodes");
Query query = dbreference.orderByKey().equalTo(currentUser); //current user is "abhishek88666kumar" in this case.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String passcode = txtPasscode.getText().toString;//Passcode is 1234 in this case.
String fetchedValue = "";
for (DataSnapshot snap : dataSnapshot.getChildren()){
fetchedValue = (String) snap.getValue();
}
if (!passcode.equals(fetchedValue)){
Toast.makeText(getApplicationContext(), "Passcode doesn't match.", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Passcode matched.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "No passcode found for this user", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Assuming pass is a value like 1234, this line:
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(...
Should be:
FirebaseDatabase.getInstance().getReference("passcodes").orderByValue().equalTo(pass).addListenerForSingleValueEvent(...
This way the DataSnapshot will contain all child nodes of passcodes that have the value 1234, i.e. "abhishek88666kumar" in your JSON sample.
Also be sure to study the documentation on sorting and filtering data.
This is the first way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passcode = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+passcode, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("passcode");
Query applesQuery = ref.orderByValue().equalTo(passcode);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+passcode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
This is the second way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+check, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("passcode");
// Query applesQuery = ref.child("Customers").orderByChild("abhishek88666kumar").equalTo(passcode);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("abhishek88666kumar")!=null){
passcode = map.get("abhishek88666kumar").toString();
if (passcode.equals(check))
{
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+check, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
Both are working.
Hope it's help full for you.
thank you.
I've successfully inserted data into my firebase database.(Client App).
Now all I have to do is to retrieve data back into a text view but in a different application.(Admin Application).
public void clients()
{
String name="Abch";
String gender="Abcg";
String barber="Abcf";
String concern="Abce";
String dt="Abcd";
if(!TextUtils.isEmpty(name) || !TextUtils.isEmpty(gender) || !TextUtils.isEmpty(barber) || !TextUtils.isEmpty(concern) || !TextUtils.isEmpty(dt))
{
String id=databaseReference.push().getKey();
client client=new client(id,name,gender,barber,concern,dt);
databaseReference.child(id).setValue(client);
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Something Went Wrong Please Check Again", Toast.LENGTH_SHORT).show();
}
}
If you want to retrieve the data in another application, you have to use eventListeners, provided you have set the rules of your database right.
There are three eventListeners you can use namely, singleValueEventListener, valueEventListener and childEventListener. Since you have not posted the structure of your database, I'm assuming you know how to get the required DatabaseReference.
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Client client = ds.getValue(Client.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addListenerForSingleValueEvent(eventListener);