Firebase Delete Child onButtonClick - java

My problem is I cant delete a single child from the firebase database, either nothing happens or it deletes the whole child and all data. I've looked around and tried multiple solutions but for whatever reason mine wont work and I out of ideas why.
Any help is appreciated.
Java class.
//get data passed from viewpasswords and put them into textviews
name.setText(getIntent().getExtras().getString("data"));
password.setText(getIntent().getExtras().getString("pass"));
//get current user id and reference to database
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userID = user.getUid();
dbRef = FirebaseDatabase.getInstance().getReference();
//button onclick stuff
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DeleteData();
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DecryptPassword.this, ViewPasswords.class);
startActivity(intent);
}
});
}
private void DeleteData() {
final String passName = name.getText().toString();
Query query = dbRef.child("Passwords").child(userID).orderByChild("PasswordName").equalTo(passName);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot itemSnapshot : dataSnapshot.getChildren()){
dataSnapshot.getRef().removeValue();
Toast.makeText(DecryptPassword.this, "Success", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DecryptPassword.this, ViewPasswords.class);
startActivity(intent);
}
}else{
Toast.makeText(DecryptPassword.this, "Failed to delete", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(DecryptPassword.this, "Error occurred sorry", Toast.LENGTH_SHORT).show();
}
});
}
Firebase Database:
Thanks.

dataSnapshot.getRef().removeValue();
Change this part to:
itemSnapshot.removeValue();

Related

Unable to retrieve and compare data from firebase in android studio

I am trying to get Data and comparing it to the input data but it doesn't do anything. Pls Help me!`btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Routes").child("route1").child("Students").child("driver");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String phoneNumber = et_phone.getText().toString();
String password = et_password.getText().toString();
String phone = dataSnapshot.child("Phone_No").getValue().toString();
String pass = dataSnapshot.child("Password").getValue().toString();
if(phone.equals(phoneNumber)){
if(pass.equals(password)){
startActivity(new Intent(Authentication.this, Home.class));
}else{
Toast.makeText(Authentication.this, "Worng Password!!!", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Authentication.this, "Invalid PhoneNumber![enter image description here][1]", Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});`

Android Retriving the data from firebase using Phone Number

I am trying to fetch the data of current user with PhoneNumber from firebase database but i am not able to fetch the data
My Application is PhoneAuthtication and i have qiven the number as a child and reference path is User What should i do to fetch the data
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(user.getPhoneNumber()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String A = String.valueOf(snapshot.child("fullName").getValue());
String B = String.valueOf(snapshot.child("phone1").getValue());
String C = String.valueOf(snapshot.child("phone2").getValue());
String D = String.valueOf(snapshot.child("message").getValue());
Name.setText(A);
Phone1.setText(B);
Phone2.setText(C);
Message.setText(D);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProfileActivity.this,HomeActivity.class);
startActivity(intent);
finish();
}
});

Check if a value exist in more then on child Firebase Database in Android

I'm developing an android application for college project using Java and Firebase. I want to store the details of faculties working in college like name,email,department etc based on their position. I have created 3 child nodes HOD,Class mentor and lecturers inside Faculties as you can see that in here.
my problem is when I want to add the members inside any one these child I want to check if that members email ID is exist in any other childs. For example I want to add a member in HOD child.If this members email existed inside Lecturers child it should display Toast user already existed as Lecturer else it should add member inside Lecturer.
I used this code.
post = "HOD";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
post = "Class mentor";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
post = "Lecturer";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
checkData();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
It works fine but it's lengthy and also it takes time to check.If there is any better solution that would be very helpful.
This is is my code complete code for adding Faculties.
public class MainActivityAddFaculty extends AppCompatActivity {
private TextInputLayout addName, addEmail;
private TextInputEditText addEditName, addEditEmail;
private Button addBtn;
private Spinner addPositionSpinner,addDeptSpinner,addYearSpinner;
private TextView addPosition,addDept,addYear;
private String sDept = "Select department",sPost = "Select position",sYear = "Select year";
private String position,department,year,post;
private boolean b = false;
private FirebaseDatabase firebaseDatabase;
private FirebaseStorage firebaseStorage;
private DatabaseReference databaseReference,databaseReference2;
private StorageReference storageReference;
LoadingDialog loadingDialog;
private String facultyID;
private String name,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_faculty);
setTitle("Add Hod");
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addName = findViewById(R.id.addFName);
addEmail = findViewById(R.id.addFEmail);
addEditName = findViewById(R.id.addFEditName);
addEditEmail = findViewById(R.id.addFEditEmail);
addBtn = findViewById(R.id.addFBtn);
addPositionSpinner = findViewById(R.id.addFPositionSpinner);
addPosition = findViewById(R.id.addFPosition);
addDeptSpinner = findViewById(R.id.addFDepartmentSpinner);
addDept = findViewById(R.id.addFDepartment);
addYearSpinner = findViewById(R.id.addFYearSpinner);
addYear = findViewById(R.id.addFYear);
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("FACULTIES");
facultyID = databaseReference.push().getKey();
loadingDialog = new LoadingDialog(MainActivityAddFaculty.this);
//selectPosition();
//TODO:Select position
List<String> categories = new ArrayList<>();
categories.add(0,"Select position");
categories.add("HOD");
categories.add("Class mentor");
categories.add("Lecturer");
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addPositionSpinner.setAdapter(dataAdapter);
addPositionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
addPosition.setText(parent.getSelectedItem().toString());
test();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityAddFaculty.this, "Select a position", Toast.LENGTH_SHORT).show();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = addEditName.getText().toString().trim();
email = addEditEmail.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(MainActivityAddFaculty.this, "Enter name", Toast.LENGTH_SHORT).show();
}else {
if (TextUtils.isEmpty(email)) {
Toast.makeText(MainActivityAddFaculty.this, "Enter email.", Toast.LENGTH_SHORT).show();
} else {
checkData();
}
}
}
});
}
private void test(){
position = addPositionSpinner.getSelectedItem().toString();
if (position.equals(sPost)){
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
}else if (position.equals("HOD")){
addDeptSpinner.setVisibility(View.VISIBLE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.VISIBLE);
addYear.setVisibility(View.GONE);
} else if (position.equals("Class mentor")){
addDeptSpinner.setVisibility(View.VISIBLE);
addDept.setVisibility(View.VISIBLE);
addYearSpinner.setVisibility(View.VISIBLE);
addYear.setVisibility(View.VISIBLE);
} else if (position.equals("Lecturer")){
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
} else {
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
}
}
private void checkData(){
position = addPositionSpinner.getSelectedItem().toString();
department = addDeptSpinner.getSelectedItem().toString();
year = addYearSpinner.getSelectedItem().toString();
if (position.equals(sPost)){
Toast.makeText(this, "Select position", Toast.LENGTH_SHORT).show();
} else if (position.equals("HOD")){
if (department.equals(sDept)){
Toast.makeText(MainActivityAddFaculty.this, "Select department.", Toast.LENGTH_SHORT).show();
} else {
AddHOD addHOD = new AddHOD(name,position,department,email,facultyID);
databaseReference.child(position).child(facultyID).setValue(addHOD).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}else if (position.equals("Class mentor")){
//add Class mentor process started
if (!department.equals(sDept)){
if (!year.equals(sYear)) {
AddClassMentor addClassMentor = new AddClassMentor(name, position, department, year, email, facultyID);
databaseReference.child(position).child(facultyID).setValue(addClassMentor).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(this, "Select year.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Select department", Toast.LENGTH_SHORT).show();
}
} else if (position.equals("Lecturer")){
AddLecturer addLecturer = new AddLecturer(name,position,email,facultyID);
databaseReference.child(position).child(facultyID).setValue(addLecturer).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Entry is pending.", Toast.LENGTH_SHORT).show();
}
}
}
Firebase's queries work on a list of nodes. Since you have a hierarchy, you'll need to fire the same query for each list you have in there, as you're doing today.
As usual when dealing with NoSQL databases, the solution is to model the data in a way that makes the use-case easiest. If you want to search across all members, store a single list of members:
"members": {
"$memberid": {
"email": "membersemail#institute.edu",
"memberType": "Class mentor" // or "HOD" or "Lecturer"
}
}
With the above structure you only have to execute one query to find all members with a specific email address.
You can either use the above structure to replace the three structures you currently have, or you can use it as an additional structure just for this use-case. Which one to choose depends on the other use-cases in your app, there is no solution that is right for all apps, just the one that works for you.
Enforcing uniques across values as you're doing here, will lead to scalability issues over time, as you:
Need to search across all members, which takes more time as you get more members.
More importantly: you will need to use a transaction to insert new users, to reduce the chances that multiple users claim the same email address at the same time.
This leads to a second scaling problem, as you'll need to run that transaction on the evert-growing /members node.
Finally: a malicious user can bypass the transaction by writing their own code, and still claim any email address.
Ensuring uniqueness on Firebase is only really enforceable if you use those values as the key in a list, so by maintaining a (additional) list of email addresses.
For more on this see:
Firebase security rules to check unique value of a child #AskFirebase
Firebase android : make username unique
How do you prevent duplicate user properties in Firebase?
Firebase realtime database validation username and email

Properly send value through many intents

I have tried all the good ole fashion ways of sending data through intents such as getExtra and putExtra. However, this certain piece of information will not travel through intents. The variable is initialized here (driverId):
private void findDriver() {
DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
GeoFire gfDrivers = new GeoFire(drivers);
GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
if(!Common.isDriverFound){
Common.isDriverFound = true;
Common.driverId = key;
btnPickupRequest.setText("CALL SUB");
Toast.makeText(Home.this,""+key, Toast.LENGTH_SHORT).show();
}
}
I then send the information for driverId when a button is clicked here:
Intent intent = new Intent(Home.this, CallDriver.class);
intent.putExtra("driverId",marker.getSnippet());
intent.putExtra("lat",mLastLocation.getLatitude());
intent.putExtra("lng",mLastLocation.getLongitude());
startActivity(intent);
I then call the information in the text intent like so:
if (driverId != null && !driverId.isEmpty())
if (getIntent() !=null) {
driverId = getIntent().getStringExtra("driverId");
}
sendRequestToDriver(driverId, mService, getBaseContext(), mLastLocation);
}
My send request to driver method is:
public static void sendRequestToDriver(String driverId,final IFCMService mService,final Context context,final Location currentLocation) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tbl);
tokens.orderByKey().equalTo(driverId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
Token token = postSnapShot.getValue(Token.class);
//String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()));
String riderToken = FirebaseInstanceId.getInstance().getToken();
Map<String,String> content = new HashMap<>();
content.put("customer", riderToken);
content.put("driverId",driverId);
content.put("lat",String.valueOf(currentLocation.getLatitude()));
content.put("lng",String.valueOf(currentLocation.getLongitude()));
DataMessage dataMessage = new DataMessage(token.getToken(),content);
Log.d(String.valueOf(dataMessage), "here big boy"+dataMessage);
mService.sendMessage(dataMessage).enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1)
Toast.makeText(context, "Request Sent!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Now when I try to receive the information on the intent RateActivity, I get a null value. How can I make sure that the string driverId is properly initialized or the data stays throughout these intents?
try this intent.putExtra("driverId",marker.getSnippet().toString());
intent.putExtra("lat",mLastLocation.getLatitude().toString());
intent.putExtra("lng",mLastLocation.getLongitude().toString());

Direct to each activity according to type of user [duplicate]

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 3 years ago.
I have created a project which has two types of user (patient and doctor). During login, I need to retrieve the role attribute in the firebase which under the users table.
In my database structure, user type maybe is "doctor" or "patient". During login, I think I need to retrieve the role information and then assign them to different activity in android studio. However, my code seems doesn't work. The application keeps stopped. Is there anyone can help me. Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
email = findViewById(R.id.email);
psd = findViewById(R.id.psd);
}
public void clicked(View v) {
switch (v.getId()) {
case R.id.login:
LoginUser();
break;
case R.id.register:
Intent intent = new Intent(this, ChooseRole.class);
startActivity(intent);
break;
}
}
public void LoginUser() {
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
indentify();
finish();
} else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void indentify() {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("role").getValue(Long.class);
String role = String.valueOf(points);
if(role=="patient"){
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
}
else{
Intent intent = new Intent(Login.this, HomePage2.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
Hi guys, I changed it like this and it is successful. Thanks for everyone helping :D
public void LoginUser(){
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("role").getValue(String.class).equals("patient")) {
startActivity(new Intent(Login.this, HomePage.class));
return;
}
if (dataSnapshot.child("role").getValue(String.class).equals("doctor")) {
startActivity(new Intent(Login.this, HomePage2.class));
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
Since in your database you have a node called users, then add a reference to that node, for example:
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Then do the following:
Change this:
if(role=="patient"){
into this:
if(role.equals("patient")){
You need to use equals() when you want to compare the value of each object.

Categories