how to use firebase query in if else condition - java

here is the code of the onclick of button , what i want to do is on click of his button app must fetch the email from the firebase database if successful it must show up in edit text that email found else show in Edit-text that email not found , here i am able to fetch the email and show that email found on Edit-text but not able to show the email not found (else part of the code ) instead i get this in console
W/PersistentConnection: pc_0 - Using an unspecified index. Consider adding '".indexOn": "email"' at /users/users to your security and Firebase rules for better performance
conbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase ref = new Firebase("https://(refrence of firebse database)");
final String searchEmail = emailcon.getText().toString().trim();
final Query query = ref.orderByChild("email").equalTo(searchEmail);
query.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot child : dataSnapshot.getChildren())
{
final String fetchEmail;
Map<?, ?> value = (Map<?, ?>) child.getValue();
Log.d("main2activity ","User data : "+ value);
fetchEmail = (String) value.get("email");
Log.d("main2activity ","User email : "+ fetchEmail);
if (searchEmail.equals(fetchEmail))
{
emailcon.setText("email found hurray "+query.getRef());
}
else
{
emailcon.setText("still no email found!!");
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});

Since you're firing a query, you will get a snapshot that can contain 0 or more children. If it contains any children, those children will have the email address you used in equalTo()
You need to handle the onDataChange() slightly differently:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
emailcon.setText("email "+searchEmail+" found at URL "+child.getRef());
}
}
else {
emailcon.setText("still no email found!!");
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});

Related

How to retrieve push() valued data from Firebase to android

I am going to make a simple app and I am completely new to Android development. I want to develop an edit button to save my data in the Realtime Database. This is my code:
holder.edite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final DialogPlus dialogPlus=DialogPlus.newDialog(holder.title.getContext())
.setContentHolder(new ViewHolder(R.layout.dialogcontent))
.setExpanded(true,2100)
.create();
View myView=dialogPlus.getHolderView();
EditText title=myView.findViewById(R.id.hTitle);
EditText description=myView.findViewById(R.id.hDescription);
Button submit=myView.findViewById(R.id.usubmit);
title.setText(myItems.getName());
description.setText(myItems.getAddHomeworkDescription());
dialogPlus.show();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String,Object> map=new HashMap<>();
map.put("name",title.getText().toString());
map.put("addHomeworkDescription",description.getText().toString());
DatabaseReference myRef = getInstance().getReference().child("Homework");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
// String key = myRef.push().getKey();
myRef.child(uid).child()
.updateChildren(map);
dialogPlus.dismiss();
}
});
}
});
This is how my firebase database looks like
What I want to add into .child() to get highlighted(In the image) Unique id direction. But this unique ID is not always same. It change everythime when user create new one.
You will either have to know the push key (-NN...) value of the node you want to update already, determine it with a query, or loop over all child nodes and update them all.
Update a specific child with a known push key
myRef.child(uid).child("-NNsQO7O9lh0ShefShV")
.updateChildren(map);
Update children matching a specific query
Say that you know you want to update the node with name "test12", you can use a query for that:
myRef.child(uid).orderByChild("name").equalToValue("test12").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot nodeSnapshot: dataSnapshot.getChildren()) {
nodeSnapshot.getRef().updateChildren(map);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
})
Update all children
This is a simpler version of the above, by removing the query condition:
myRef.child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot nodeSnapshot: dataSnapshot.getChildren()) {
nodeSnapshot.getRef().updateChildren(map);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
})

Firebase data retrieving issue in android studio

I want to retrieve data from firebase and display it on recycle view. I provided the correct path for data retrieving. But there is some problem i am unable to find it.
This code where i provided the child address.
final DatabaseReference nm= FirebaseDatabase.getInstance().getReference("Cart")
.child("Admin view")
.child(phoneNo)
.child("Products");
nm.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot npsnapshot : dataSnapshot.getChildren())
{
cart l=npsnapshot.getValue(cart.class);
listData.add(l);
}
adapter = new cartAdapterr(listData, AdminShowOrderProductsActivity.this);
rv.setAdapter(adapter);
}
else
{
Toast.makeText(AdminShowOrderProductsActivity.this, "No Data for: " + phoneNo, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
That is the screenshot of my firebase database and emulator. the phone number in toast message which is also present in firebase database. on node Phone number is correct but it shows error.
The way you work is correct, but you have a mistake, which is when the data is modified in Firebase, a new cartAdapterr is created and this operation is wrong.
You must first create an Adapter and then send the data.
for example you can create it onCreate and create a method inside the Adapter that receives List <Cart> as Shown below :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//..
adapter = new cartAdapterr(this);
loadDataFirebase():
}
void loadDataFirebase(){
final DatabaseReference nm= FirebaseDatabase.getInstance().getReference("Cart")
.child("Admin view")
.child(phoneNo)
.child("Products");
nm.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot npsnapshot : dataSnapshot.getChildren())
{
cart l=npsnapshot.getValue(cart.class);
listData.add(l);
}
adapter.setDataList(listData);
}
else
{
Toast.makeText(AdminShowOrderProductsActivity.this, "No Data for: " + phoneNo, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
In Adapter you have to create this setDataList (List<Cart> cartItems) :
public void setDataList (List<Cart> cartItems ) {
this.cartItems = cartItems;
notifyDataSetChanged();
}

Getting values from Firebase

I'm new to Firebase, and decided to get my feet wet. However, I'm having trouble retrieving values from a query. I'm basically trying to get the password value, but I believe it's returning nothing.
Error:
java.lang.NullPointerException: println needs a message
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
db.child("Users").orderByChild("username").equalTo(username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Get the password,and check it against the password field
Map<String, String> map = (Map<String, String>)dataSnapshot.getValue();
Log.d("result", map.get("password"));
} else {
Toast.makeText(getApplicationContext(), "Incorrect login details", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
I know this isn't very practical, but like I said I'm only practicing.
Thanks for the help!
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.
The code in your onDataChange needs to take care of the fact that the snapshot is a list, by looping over its snapshot.getChildren():
db.child("Users").orderByChild("username").equalTo(username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
//Get the password,and check it against the password field
Map<String, String> map = (Map<String, String>)snapshot.getValue();
Log.d("result", map.get("password"));
}
}
Sine your database structure is different than your reference in your code you should change some things
First your Reference to the data should be like this
db.child("Users").child(uid).child("password").addValueEventListener...
Where uid is the result of
private FirebaseAuth mAtuh;
mAuth = FirebaseAuth.getCurrentUser().getUid();
String uid = mAuth ;
Check the official doc on how to properly authenticate users
https://firebase.google.com/docs/auth/android/manage-users
Also you can implement google sign-in :
https://firebase.google.com/docs/auth/android/google-signin
And then you can retrieve your password field like this
// Attach a listener to read the data
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String password = dataSnapshot.getValue(String.class);
Log.e("The password is:",""+password);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Error getting the password",""+databaseError.getCode());
}
});
Hardcoding your reference without mAuth will be like this
db.child("Users").child("L7VR2mGZKnbReFqOlmP").child("password").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String password = dataSnapshot.getValue(String.class);
Log.e("The password is:",""+password);
}else
{
Toast.makeText(getApplicationContext(), "Incorrect login details", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Error getting the password",""+databaseError.getCode());
}
});
Hope it helps
happy coding

How to compare firebase inner child items in android without data object model?

I'm trying to validate the admin by taking text from the app. I've tried using a data object model and store the details but it is just not required. I've tried this code in other classes without the loop and it works fine.
databaseReference = FirebaseDatabase.getInstance().getReference("Preschools");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot preschool : dataSnapshot.getChildren())
{
for(DataSnapshot admin : preschool.getChildren())
{
String f_em = (String) admin.child("Admin").child("Email").getValue();
String f_pa = (String) admin.child("Admin").child("Password").getValue();
if(emailAddress.getText().toString().equals(f_em) && password.getText().toString().equals(f_pa))
{
flag = true;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(_2_Login.this, "Unable to reach firebase", Toast.LENGTH_SHORT).show();
}
});
Logacat : Image Here
False is returned in the if condition. I'm not able to figure out the error in my logic.
Error : No break if credentials are equal.
Below is the correct code:
databaseReference = FirebaseDatabase.getInstance().getReference("Preschools");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot preschool : dataSnapshot.getChildren())
{
if(emailAddress.getText().toString().equals(preschool.child("Admin").child("Email").getValue()) &&
password.getText().toString().equals(preschool.child("Admin").child("Password").getValue()))
{flag=true; break;}
}

How to add a counter in firebase?

So guys, I had the database: Event and User.
When some user has interest in some event clicking the button, this will add a child in eventHasInterest with the user in Event database, and in the database User will add the event that has interest. It's already working, but I need to put a counter to show, how many people has interest, and it's not working, only add once. I need one click, +1, another click -1 on.
btn_interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseEvent.child(getKeyEvent()).addListenerForSingleValueEvent( //get the event by key
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Event event = dataSnapshot.getValue(Event.class);
user = FirebaseAuth.getInstance().getCurrentUser(); //get the user logged in
if(user != null) {
databaseUser.orderByChild("userEmail").equalTo(user.getEmail()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
final User user = userSnapshot.getValue(User.class); // user data logged in
databaseUser.orderByChild("userHasInterest").equalTo(event.getEventId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
databaseUser.child(user.getUserId()).child("userHasInterest").child(event.getEventId()).setValue(event.getEventId());
databaseEvent.child(event.getEventId()).child("eventAmount").setValue(dataSnapshot.getChildrenCount()+1);
} else {
//event already exists
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseEvent.orderByChild("eventHasInterest").equalTo(user.getUserId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
databaseEvent.child(event.getEventId()).child("eventHasInterest").child(user.getUserId()).setValue(user.getUserId());
} else{
//user already exist
}
}
My firebase:
dataSnapshot.getChildrenCount() does not return the int value of eventAmount, it returns the number of children that eventAmount has. In your case, eventAmount will always return 0 since there is no children of eventAmount. I suggest that instead of using getChildrenCount, get the value of the dataSnapshot, and parse that value into an int. After that, increment that value by 1, and store that value instead.
databaseEvent.child(event.getEventId()).child("eventAmount").setValue(Integer.parseInt(dataSnapshot.getValue().toString()) + 1);
EDIT: As suggested by Frank, storing the value using a transaction is recommended to help avoid concurrent updates. I used this post, as well as the post Frank linked to help write the code.
public void updateCount(DatabaseReference database){
database.runTransaction(new Handler() {
#Override
public Result doTransaction(MutableData mutableData) {
//Currently no value in eventAmount
if(mutableData.getValue() == null){
mutableData.setValue(1);
}
else{
mutableData.setValue(Integer.parseInt(mutableData.getValue().toString()) + 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
//Probably log the error here.
}
});
}
So in your "userHasInterest" onDataChange method, call my method above like this.
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(!dataSnapshot.exists()) {
databaseUser.child(user.getUserId()).child("userHasInterest").child(event.getEventId()).setValue(event.getEventId());
updateCount(databaseEvent.child(event.getEventId()).child("eventAmount")); //New line here
} else {
//event already exists
}
}

Categories

Resources