Chris Chris - 3 years ago 260
Android Question

How can I validate / check if string value exists in Firebase database (Android)

I've created AutoCompleteTextView for Ingredient, it works perfect. The DB save also works, I've tested it without validation.
If Ingredient exists in Firebase db I want to add recipe to DB.
For example if

RecipeIngredients="milk"
recipe should be saved to DB.

Here's my code.

DatabaseReference ingDBref = FirebaseDatabase.getInstance().getReference("Ingredients");
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference("Recipes");

public void addRecipe(){
final String RecipeName=RecipeNameEditText.getText().toString();
final String RecipePrepareTime=PrepareTimeEditText.getText().toString();
final String RecipeIngredients=IngredientsACTV.getText().toString();
final String RecipeDescription=DescriptionEditText.getText().toString();
final String RecipeDifficulty=DifficultySpinner.getSelectedItem().toString();
key=databaseReference.push().getKey();

ingDBref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child(RecipeIngredients).getValue()!=null){

Recipes recipes=new Recipes(key,RecipeName,RecipeDifficulty,RecipePrepareTime,RecipeIngredients,RecipeDescription);
databaseReference.child(key).setValue(recipes);
Toast.makeText(AddRecipeActivity.this,"Saved...",Toast.LENGTH_LONG).show();

}
else{
IngredientsACTV.setText("");
Toast.makeText(AddRecipeActivity.this,"Error...",Toast.LENGTH_LONG).show();
}
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});


Firebase DB

enter image description here

Answer Source

if(data.child("ingredientName").getValue().equals(RecipeIngredients)) Solved my problem. Thanks for the advice g

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download