Iterate function to search for a key on Firebase, Android Studio? - android

Hi I am making an app where you enter a number in an EditText, if that number matches with some key from the database in Firebase it will show up the value of that key in a TextView.
Here's the structure of the database:
Structure DB
The problem i have is that when i enter "1" in my EditText and it searches for the key that matches with it in the database i can retrieve the value of it because it's the first child (i guess) but when i enter another key (2-5) it says that doesn't exists because of the else sentence in my code.
I think i'm not iterating the full database so i can retrieve the correct value.
Here's the code:
public class MainActivity extends AppCompatActivity {
private DatabaseReference mDatabase;
private TextView mEstado ;
private Button B_buscar;
private EditText E_buscar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("no_orden");
mEstado = (TextView) findViewById(R.id.estado);
B_buscar = (Button) findViewById(R.id.B_buscar);
E_buscar = (EditText) findViewById(R.id.E_buscar);
B_buscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String buscar = E_buscar.getText().toString().trim();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot estado = dataSnapshot.getChildren().iterator().next();
if (estado.getKey().toString().equals(buscar)){
mEstado.setText("The number #" + buscar + " contains: " + estado);
}else{
if (buscar.equals("")){
mEstado.setText("Enter a valid number.");
}else {
mEstado.setText("The number #" + buscar + " doesn't exists.");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}}
Hope someone can help me.
Thanks.

You can use a for iterator like this:
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "Key: "+postSnapshot.getKey());
Log.d(TAG, "Value: "+postSnapshot.getValue());
}

So you are trying to send a string called buscar and you want to check its existance, I suggest you do this :
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//in this part of your code use this
if(dataSnapshot.hasChild(buscar)){
//this means the number is found in the database
}else{
//this means the number is not found in the database
}
}

Related

Retrieve data from Firebase database in values form

mDatabase6 = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading");
mCO2View = (TextView) findViewById(R.id.CO2value);
mDatabase6.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (com.google.firebase.database.DataSnapshot datasnap: dataSnapshot.getChildren()){
String CO2level = datasnap.child("CO2").getValue(String.class);
mCO2View.setText("CO2: " + CO2level + "ppm");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCO2View.setText("CO2: Error");
}
});
I try to retrieve data that will be updated every interval of time, this code is for retrieve data that store in database in string form, I would like to retrieve the CO2 in values form. Pls get a help. Thanks

App Stopped - Retriving data from firebase

I don't know whats wrong with the code..
when I enter the information , my app shows - unfortunately stopped.
To access the both zone , I have declared the String at the top.
IDE also doesn't show any error.
I have also followed some answers from stackoverflow but , the error remains the same.
I want to retrieve data from here
My code is -
public class LoginPage extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef;
String name, password, email, edtName, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
final EditText uname, pass;
Button login, signup;
uname = (EditText) findViewById(R.id.editUsername);
pass = (EditText) findViewById(R.id.editPassword);
login = (Button) findViewById(R.id.buttonLogin);
signup = (Button) findViewById(R.id.buttonSignup);
edtName = uname.getText().toString();
edtPassword = pass.getText().toString();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LoginPage.this, "Button Tapped", Toast.LENGTH_SHORT).show();
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("sampBase");
DatabaseReference zone1Ref = zonesRef.child(name);
DatabaseReference zone1NameRef = zone1Ref.child("Name");
DatabaseReference zone1PassRef = zone1Ref.child("Password");
// name retrive
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
name = dataSnapshot.getValue(String.class);
Toast.makeText(LoginPage.this, name+" is name", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// password retrive
zone1PassRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
password = dataSnapshot.getValue(String.class);
if(password != edtPassword){
Toast.makeText(LoginPage.this, "Wrong password.!", Toast.LENGTH_SHORT).show();
pass.setText("");
return;
}
else{
Toast.makeText(LoginPage.this, "Login Successful.!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginPage.this, HomePage.class);
i.putExtra("Name", name);
startActivity(i);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
You haven't assigned asharfulais value to name variable.
As I have read your code, I couldn't notice the assignment. If I am correct, your name is null, and you cannot pass null to child() method.
You can fix this by simply assigning the value before getting any further (deeper) refereences.
name ="asharfulais";
Notes:
As your app could have more users, you should consider retrieving user's ID's rather than declaring their usernames.
It's good practice to declare string variables (children names in database) that never change as constants in a separate class (E.g. Constants.java).

How do I save user information using Firebase with user enter unique id in android?

I am implementing an application using FireBase, in this application I have to save user information with user enter unique id. How can I do that. Actually it saving the data with random generated value. But I want to add a user enter unique id.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
txtDetails = (TextView) findViewById(R.id.txt_user);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
btnSave = (Button) findViewById(R.id.btn_save);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue("Realtime Database");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
// update toolbar title
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email);
} else {
createUser(name, email);
}
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Save");
}
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
userId = mFirebaseDatabase.push().getKey();
}
User user = new User(name, email);
mFirebaseDatabase.child(userId).push().setValue(user);
addUserChangeListener();
}
/**
* User data change listener
*/
private void addUserChangeListener() {
// User data change listener
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
// Check for null
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);
// Display newly updated name and email
// txtDetails.setText(user.name + ", " + user.email);
// clear edit text
inputEmail.setText("");
inputName.setText("");
toggleButton();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read user", error.toException());
}
});
}
private void updateUser(String name, String email) {
// updating the user via child nodes
if (!TextUtils.isEmpty(name))
mFirebaseDatabase.child(userId).child("name").setValue(name);
if (!TextUtils.isEmpty(email))
mFirebaseDatabase.child(userId).child("email").setValue(email);
}
To save user data under an unique identifier i suggest you using the email address in stead of pushing a new key or using the uid. The email address is unique and easy to use. But because Firebase does not accept . symbol in the key i suggest you encode the email address like this:
name#email.com -> name#email,com
As you see, i have changed the the dot symbol . with a coma ,. To achive this i recomand you using this methods:
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}
Hope it helps.

How to check existed data in firebase?

I am using firebase database, but I am newbie with it. I am following this tutorial,
Now, my question is how can I check the email if it is already exist in the database? If email is already there data should not be add to db.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView txtDetails;
private EditText inputName, inputEmail;
private Button btnSave;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying toolbar icon
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
txtDetails = (TextView) findViewById(R.id.txt_user);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
btnSave = (Button) findViewById(R.id.btn_save);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue("Realtime");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
String appTitle = dataSnapshot.getValue(String.class);
// update toolbar title
getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email);
} else {
updateUser(name, email);
}
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Your Logic here
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
User mModel = eventSnapshot.getValue(User.class);
// Log.e("DATA" ,""+ mModel.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Update");
}
}
private void filter()
{
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
userId = mFirebaseDatabase.push().getKey();
}
User user = new User(name, email);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
/**
* User data change listener
*/
private void addUserChangeListener() {
// User data change listener
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(!dataSnapshot.child("users").child("email").exists())
{
Log.e(TAG, "User not exists");
}
else
{
Log.e(TAG, "User exists");
}
// Check for null
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);
// Display newly updated name and email
txtDetails.setText(user.name + ", " + user.email);
// clear edit text
inputEmail.setText("");
inputName.setText("");
toggleButton();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read user", error.toException());
}
});
}
private void updateUser(String name, String email) {
// updating the user via child nodes
if (!TextUtils.isEmpty(name))
mFirebaseDatabase.child(userId).child("name").setValue(name);
if (!TextUtils.isEmpty(email))
mFirebaseDatabase.child(userId).child("email").setValue(email);
}
}
Inside ValueEventListener() check email address is exist or not
Try this
if(!dataSnapshot.child("users").child("email").exist)
then insert new value
If you are trying to create a rule for block user have 2 accounts with same email, you can use the rules inside firebase. There are rules ready for this.
Authentication -> Method -> botton functions.

How to fetch all data after adding new data in firebase database

This is my code for adding person object in firebase.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Person");
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
person.setName(name);
person.setAddress(address);
new Firebase(Config.FIREBASE_URL).child("Person").push().setValue(person);
}
});
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: " + person.getName() + "\nAddress: " + person.getAddress() + "\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
Adding data is working fine and every add creating a new key for person.
But addValueEventListener is showing me only last added entry. I want all the entries data.
Can anyone help me on this?
Every time anything changes in the Person node, you get notified through onDataChange(). In there you loop over the people and then for each call:
textViewPersons.setText(string);
So you're constantly replacing the contents of the text view with the information from each person. After each loop it will end up showing just the information for the last user. You can easily see that the code loops through all people by adding:
System.out.println(string);
With this you'll see each person in logcat, but only the last person in the text view.
One solution is to either use a ListView or RecyclerView, both of which handle lists of items. Another (quicker to implement) way to show all users it to append the strings in the text view:
textViewPersons.setText(textViewPersons.getText()+string+"\n");
Try this if it helps:
String dataviewer=new String();
Firebase firebase=new Firebase(Config.FIREBASE_URL);
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
person.setName(name);
person.setAddress(address);
new Firebase(Config.FIREBASE_URL).child("Person").push().setValue(person);
}
});
firebase.child("Person").addChildEventListener(new ChildEventListener() {
// Retrieve values as they are added to Firebase
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Map<String,Object> vals=(Map<String,Object>)snapshot.getValue();
String name_person=String.valueOf(vals.get("name"));
String address_person=String.valueOf(vals.get("address"));
dataviewer+="Name: " + name_person + "\nAddress: " + address_person + "\n\n";
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});

Categories

Resources