how to stop slash from splitting the firebase database child - android

I am working on an App that allows the student to register using their registration number. the registration number is like 17/csc/001 till infinity. The student registration number will saved as a child of that firebase reference but the issue I am having is that firebase splits the registration number into three places due to the slash that's found there. I need help on how to resolve it because there's no how a student's registration number will be without the slash.
I need something like this "Registration Numbers","17/csc/001" but I am having this
"Registration Numbers": {
"17": {
"CSC": {
"001": {
"registrationNumber": "17/CSC/001"
}
}
}
}
void addRegistrationNumber(){
progressBar.setVisibility(View.VISIBLE);
String regNumber = editText.getText().toString();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child("Registration Numbers").child(regNumber).exists()){
progressBar.setVisibility(View.GONE);
showMessage("Error","You have Already Added this Registration Number");
}else {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("registrationNumber",regNumber);
databaseReference.child("Registration Numbers").child(regNumber).updateChildren(hashMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Registration Number Added Successfully", Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Error Occurred, Please try Again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Database error "+error.toString(), Toast.LENGTH_SHORT).show();
}
});
}

The / character is not allowed to be present in keys in the Firebase Realtime Database. So there's no way for you to include them in the keys.
What you'll want to do instead is to encode the / values in your student registration numbers, with a value that can't occur in those numbers but is allowed in the database keys. For example, if _ can't occur in your student registration numbers, then you could encode 17/csc/001 as 17_csc_001.

Related

How to create query for searching enrollment number into the Firebase realtime database for if user entered enrollment number exist or not

I've created String userenrollment that store user entered enrollment number into it! and My firebase real time database looks like .
and I tried one query but it directly goes to else block saying data doesn't exist!
ref = FirebaseDatabase.getInstance().getReference();
Query query = ref.child("Information").orderByChild("enrollment").equalTo(userenrollment);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount()>0) {
Toast.makeText(loginstudentdemo.this, "User exist!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(loginstudentdemo.this, "User doesn't exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(loginstudentdemo.this, "Database Error", Toast.LENGTH_SHORT).show();
}
});

Finding if Email and/or Username existing in Firebase - Android

I'm new to Firebase and Android so please be easy with me here.
I'm trying to validate if the username and/or email already in the DB.
The problem is that once the code finds out there no user with that username, he go to addUser() function that adds the username to the Fire-base.
I tried reading around the Android Studio Development and I get the manage single check for either Email or Username but not both.
old code :
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can someone help or direct me to an article that demonstrate 2 checks with Firebase?
edit: I found out that I need to first to orderByChild the index im searching at so I solved the Email part but the Username part is still tricky as I'm getting back an Object instead of a String and I can't convert it
New Code:
ref.equalTo(Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So if mixing both of my codes you will get the result I wanted.
In order to check if a username is in the DB I used the first part of my code and for the Email the second one
Full code for check if username and/or Email is used in Fire-base
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you have questions, feel free to ask :)

How to avoid NullPointerException when deleting a document in Firestore?

I want to give the user in my app the possibility to delete his account so when he clicks on the delete button a document gets deleted which contains all his informations. The name of the document is his displayName so I get this as a string but when I run the code you are seeing below I get a NullpointerException in this line:
String currentUsername = user.getDisplayName();
even though the displayName is not null.
Edit:
I found the solution on my own, see the answer below.
Here is my method:
btn_delete_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
deleteDocument();
}
}
});
}
});
...
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String currentUsername = user.getDisplayName();
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Your account was successfully deleted.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
First thing you have to check that current user is not null
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
if current user is not null then get its name and further check that it's name is not null.
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
if name is not null then go for delete document as follows :
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Dein Account wurde erfolgreich gelöscht.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
I think you're misunderstanding the error. It's saying that user is null, not the display name. This means there is currently no user signed into the app. You will have to write some code to check for this case.
I also strongly suggest not using a display name as the ID for a document in Cloud Firestore. Since you're using Firebase Authentication, the user already has a unique ID assigned to their account. This is the preferred way to store per-user data.
I found the error:
I called my delete method after I used the user.delete() method which deletes the signed in user, so logically the displayName was also deleted.

Fetch and Compare Key and Value from Firebase Realtime Database

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.

How to check child in firebase database?

i need to avoid duplication of data in the table.
when ever a new user add some information to the database if the "category" field data is present then need to show this data is already present in the database.
if(!group_link.isEmpty()&&!group_name.isEmpty()&&e2.length()<=50 && e2.length()>=40&&(e2.getText().toString().contains("https://chat.whatsapp.com/"))) {
HashMap<String, String> datamap = new HashMap<String, String>();
datamap.put("category", selected_item);
datamap.put("group_name", group_name);
datamap.put("group_link", group_link);
datamap.put("group_type",group_type);
datamap.put("language",language);
datamap.put("report_status",count);
mref.push().setValue(datamap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Usr_add.this, "Data Submited successfully :) ", Toast.LENGTH_SHORT).show();
e1.setText("");
e2.setText("");
} else
Toast.makeText(Usr_add.this, "Something Wrong :( ", Toast.LENGTH_SHORT).show();
}
});
}
i need to check if category data field is present or not.
DatabaseReference rf = FirebaseDatabase.getInstance().getReference();
DatabaseReference retrieve =
rf.child("type").child("Whatsapp").child("Shopping deals");
retrieve.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot getdata : dataSnapshot.getChildren()){
if (getdata.child("category").exists()) {
Toast.makeText(this,"Stop it exists!!!",Toast.LENGTH_SHORT).show();
}}else{
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First you query on shopping deals, since there is a random key there you have to a for loop to be able to reach the name:value. Then using the exists() you can see if any attribute exists in your firebase database. In this case we are checking if category exists by using child("category")
If it exists then add a Toast to the user or watever you want.. if it does not exist then maybe add it to the database using setValue()

Categories

Resources