how to check query in firestore? - java

Image attached for reference of firestore
trying to check the query in firestore to know if the user has sent the request or received it and it can perform the task accordingly and change the text of button.
firebaseFirestore.collection("users").document(userid).collection("request").whereEqualTo("userid",otherUserid).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
List<DocumentSnapshot> document = task.getResult().getDocuments();
if(document.contains("received")){
current_state="req_received";
send.setText("Accept Request");
}else if(document.contains("sent")){
current_state = "req_sent";
send.setText("Cancel Request");
}
}
}
});
The following code is to send or cancel the Request and it working fine but when I go back to another activity and come back again then the text of button changes to send request which must have stayed to cancel request as the request has already been sent.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userid.equals(otherUserid)) {
Toast.makeText(ProfileActivity.this, "Cannot send request to your own", Toast.LENGTH_SHORT).show();
return;
}
//--------Not friends.....
send.setEnabled(false);
if (current_state.equals("not_friends")) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, String> profile = new HashMap<>();
profile.put("userid", otherUserid);
firebaseFirestore.collection("users").document(userid).collection("request")
.document("sent").set(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, String> profile = new HashMap<>();
profile.put("userid", userid);
firebaseFirestore.collection("users").document(otherUserid).collection("request")
.document("received").set(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
send.setEnabled(true);
current_state = "req_sent";
send.setText("Cancel Request");
Toast.makeText(ProfileActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(ProfileActivity.this, "Failed sending request", Toast.LENGTH_SHORT).show();
}
}
});
}
//-------- Cancel request.......
if (current_state.equals("req_sent")) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
Map<String, Object> profile = new HashMap<>();
// String userid = firebaseAuth.getCurrentUser().getUid();
profile.put("userid", FieldValue.delete());
firebaseFirestore.collection("users").document(userid).collection("request")
.document("sent").update(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, Object> profile = new HashMap<>();
profile.put("userid", FieldValue.delete());
firebaseFirestore.collection("users").document(otherUserid).collection("request")
.document("received").update(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
send.setEnabled(true);
current_state = "not_friends";
send.setText("Send Request");
Toast.makeText(ProfileActivity.this, "Request canceled", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(ProfileActivity.this, "Failed request canceled", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}

As you confirmed, if the error lies only on the comparison part changing the query iteration like below might fix the issue.
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if(document.getId().contains("received")){
current_state="req_received";
send.setText("Accept Request");
// do pending stuffs or break the loop here
} else if(document.getId().contains("sent")){
current_state = "req_sent";
send.setText("Cancel Request");
// do pending stuffs or break the loop here
}
}
}
ref: https://firebase.google.com/docs/firestore/query-data/queries

Related

Link two tables in firebase using Id in android studio using Java

have a problem, I'm working on a university project, I have two tables in firebase, the gallery table that contains the photos of the itinerary and the itinerary table that contains the various itineraries of the users now I have to make sure that the id of the itinerary and the ID of the image so as to have a photo corresponding to each itinerary ì, also created by the same user. I did so:
public void addImageItinerary() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
if (images != null) {
StorageReference itineraryRef = storageReference.child("itinerary_image/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpg");
itineraryRef.putFile(images).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
itineraryRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String itineraryId = referenceDb.child("Itinerary").push().getKey();
Log.i("itineraryId", itineraryId);
HashMap<String, Object> map = new HashMap<>();
map.put("image", uri.toString());
referenceDb.child("Gallery").child(FirebaseAuth.getInstance().getCurrentUser().getUid()+ "/" + itineraryId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// APRO SCHERMATA MAPPA
// openMapFragment();
Toast.makeText(insertImage_fragment.getActivity(), "ok", Toast.LENGTH_SHORT).show();
} else {
//ERRORE
Toast.makeText(insertImage_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertImage_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else{
Toast.makeText(insertImage_fragment.getActivity(),"Please add image", Toast.LENGTH_SHORT).show();
}
}
enter image description here

Firebase android studio not inserting data correctly

This is the data being inserted the the correct one is the yay#gmail.com while the incorrectly inserted ones are the ones with a:Name
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Teachers teachers = new Teachers(user, pass, email);
FirebaseDatabase.getInstance().getReference("Teachers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(teachers).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterTeacher.this, "Teacher has been registered!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(RegisterTeacher.this, TeacherLogin.class);
startActivity(i);
}
else {
Toast.makeText(RegisterTeacher.this, "Failed to register!", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(RegisterTeacher.this, "Failed to register! Try again!", Toast.LENGTH_SHORT).show();
}
}
});

How can I change an exist list, to a new list? || android - firebase realtime database

I want to change the exist “categories” list, to a new list.
I know that my problem is in the “setPriority()”, but I don’t find the right method.
My Database Structure:
My code:
private void updateData() {
database = FirebaseDatabase.getInstance();
mDatabaseRef = database.getReference();
mDatabaseRef
.child("users")
.child(Login.userId)
.child("categories")
.setValue(categories)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//Update success
} else {
//Update fail
}
}
});
}
Thank you.
No need to query to database to update list. You can simply call setValue to over write the existing list with new one. Check below:
database = FirebaseDatabase.getInstance();
mDatabaseRef = database.getReference();
mDatabaseRef
.child("users")
.child(Login.userId)
.child("categories")
.setValue(categories)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//Update success
} else {
//Update fail
}
}
});

How to display specific data of current user from firebase to new activity?

I have a problem with my codes whereby I cannot display data (input from the previous activity) to a new activity.
this is my data in the firebase
this is my current output, the BMI is null
what I want is this, the BMI value is not null
Here is my current code of HomepageActivity:
private void viewBMI() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference myRef = database.getReference("Users").child("bmi").child(uid);
// Read from the database
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String finalBmi = (String) dataSnapshot.getValue();
showBMI.setText("BMI: " + String.valueOf(finalBmi));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Failed to read value
//Log.w(BMI, "Failed to read value.", error.toException());
}
});
This is the code from previous activity:
private void updateBMI(double bmi, final FirebaseUser currentUser) {
kg = Double.parseDouble(inputKg.getText().toString());
m = Double.parseDouble(inputM.getText().toString());
metricFormula = new MetricFormula(kg, m);
imperialFormula = new ImperialFormula(kg, m);
//bmi = String.valueOf(TWO_DECIMAL_PLACES.format(metricFormula.computeBMI(metricFormula.getInputKg(),metricFormula.getInputM())));
bmi = Double.parseDouble(TWO_DECIMAL_PLACES.format(metricFormula.computeBMI(metricFormula.getInputKg(),metricFormula.getInputM())));
final double finalBmi = bmi;
mAuth.updateCurrentUser(currentUser).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Map<String, Object> values = new HashMap<>();
values.put("bmi", finalBmi);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(values).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
//acc successfully registered
showMessage("Account Updated");
updateUI();
}
else{
}
}
});
}
}
});
}
});
}
//next page
private void updateUI() {
Intent homepageActivity = new Intent(EditProfileActivity.this,HomepageUser.class);
//homepageActivity.putExtra("bmi",bmi); //new
startActivity(homepageActivity);
finish();
}
I think,
Your reference is not reaching correctly
DatabaseReference myRef = database.getReference("Users").child("bmi").child(uid);
there is no child "bmi" under "Users"
In your image, you have
Users -> JKkaSDGLdkM7HxzBKf1ivJ4G6A03 -> bmi...etc
there is another layer you need to account for reaching the information.
Your order of child access is incorrect. As i can see in the image of Firebase Child Hierarchy you have 'bmi' under 'userID'. So replace
DatabaseReference myRef = database.getReference("Users").child("bmi").child(uid);
with
DatabaseReference myRef = database.getReference("Users").child(uid).child("bmi");
Since hierarchy structure is Users->id->bmi(a component of jason object)

error with updating user information firebase

so i am creating a sign up page and connect that with firebase users
i am recieving error with updating profile
my code goes as follow:
for creating new user i use
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.v("SignUp", "222222222222222222222222222");
Toast.makeText(SignUp.this, "SignUp failed",
Toast.LENGTH_SHORT).show();
} else {
Log.v("SignUp", "333333333333333333333333333");
uploadImage();
}
}
});
and the uploadImage() method is
public void uploadImage() {
if (image != null) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference main = storage.getReferenceFromUrl("link to my account");
StorageReference storageReference = main.child("images/" + image.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(image);
//addonFailurelistener too
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.v("SignUp", "777777777777777777777777");
String download = taskSnapshot.getDownloadUrl().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.build();
//i tried here with .setDisplayName(name)
//and with setPhotoUri(Uri.parse(download)
FirebaseAuth.getInstance().getCurrentUser().updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "8888888888888888888888888888");
addDatabase();
} else {
FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "999999999999999999999999999");
Toast.makeText(SignUp.this, "Error Occuered While setting your account", Toast.LENGTH_LONG);
finish();
startActivity(new Intent(SignUp.this, SignUp.class));
} else {
Log.v("SignUp", "..........................");
Toast.makeText(SignUp.this, "Error Cannot be resolved \n please try with another Email", Toast.LENGTH_LONG);
finish();
}
}
});
}
}
});
}
});
}
and my logcat get output like that
V/SignUp: 333333333333333333333333333
V/SignUp: 777777777777777777777777
V/SignUp: ..........................
i followed the firebase guide but looks like i am doing something wrong
any idea why it doesnt work? thanks
i get it automatically resolved after waiting for 24 hours so i am assuming account get blocked for 24h after some number of logIn in a single day

Categories