Unable to update profile values in firebase android java - java

This is the code I am using but I could not able to update values in firebase..
Database level is like:
users-> userID: fname,phone,country
I am trying to update phone number and name. I am using firebase authentication.
DatabaseReference reference;
onCreate{ encloded in
reference = FirebaseDatabase.getInstance().getReference("users").push();
public void updateProfile(View view) {
if (isNameChanged() || isPhoneChanged()) {
//Toast.makeText(this, "Updated Successfully", Toast.LENGTH_SHORT).show();
} else Toast.makeText(this, "No Change Observed", Toast.LENGTH_SHORT).show();
}
private boolean isPhoneChanged() {
if (!pphone.equals(e_pphone.getText().toString())) {
reference.child(userID).child("phone").setValue(e_pphone.getText().toString());
pphone=e_pphone.getText().toString();
return true;
} else
return false;
}
private boolean isNameChanged() {
if (!pname.equals(e_pname.getText().toString())) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser!=null) {
reference.child(userID).child("fname").setValue(e_pname.getText().toString());
pname = e_pname.getText().toString();
Toast.makeText(this, userID, Toast.LENGTH_SHORT).show();
}
return true;
} else {
Toast.makeText(this, "NOOOO "+pname, Toast.LENGTH_SHORT).show();
return false;
}
}

Hy, as you're referencing new path every time i.e.
FirebaseDatabase.getInstance().getReference("users").push();
here push() will generate new value not one which already exist in your database.
as a result dataRef won't get a path and it won't update any information.
reference = FirebaseDatabase.getInstance().getReference("users").push();
instead of push() try with any static data first and then you'll get the idea where the actual problem is.
Finally retrieve the node value which you want to update that you'll be using after "users" in firebaseReference.

Related

ArrayList in andrid does not return data while fetching data from firebase database

I am trying to get records from firebase database and return all the record within a array list but inside the for loop it will add records but when we check outside the loop it does not contain records. can anyone please help me i am new in android.Here is the code for fetching data..
public class DataBaseManagement {
public static ArrayList<Property> getAllProperties(Context context, DatabaseReference dbProperty){
ArrayList<Property> propertyList = new ArrayList<Property>();
dbProperty.get().addOnSuccessListener(new OnSuccessListener<DataSnapshot>() {
#Override
public void onSuccess(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Property tempProp;
for (DataSnapshot aProp: dataSnapshot.getChildren())
{
tempProp = aProp.getValue(Property.class);
propertyList.add(tempProp);
}
Toast.makeText(context, "Total Properties : " + propertyList.size(), Toast.LENGTH_SHORT).show(); // Here it will show the number of records
}
else {
Toast.makeText(context, "No record found", Toast.LENGTH_SHORT).show();
}
}
});
Toast.makeText(context, "Total Properties : " + propertyList.size(), Toast.LENGTH_SHORT).show(); // here it will not show the number of records
return propertyList;
}
}
as I know in addOnSucessListener it works in background thread
the fun will return and finish the background thread I think if you want it change return fun to void and use out fun liveData and update it inside addOnSucessListener

How to check if user entered userid already exists in the firebase through java?

I've tried so many ways to check if a user id is already in the firebase but all method are in vain.
Below is my code to check if user id exists but whatever data I enter it does not show the required error.
userid = findViewById(R.id.userid);
String userVal = userid.getEditText(). getText().toString();
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
if(userquery) {
userid.setError("This user name already exists");
return;
}
Whenever I try to add existing value in the input it accepts the value and overwrites in the database.
Here is the screenshot of my firebase database.
Your code so far only sets up a query. It doesn't actually execute the query, so there's no way it can detect whether the data exists. To execute a query, you have to attach a listener to it.
So in your case, that could be something like:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else if (task.getResult().exists()) {
userid.setError("This user name already exists");
}
}
});
On older SDK versions the equivalent would be:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userid.setError("This user name already exists");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Why is my function returning before document/data retrieval from firestore is complete?

I am trying to make a function that checks if a username is taken or if it is available, how I have it in firestore is that the UniqueID is the username and not a field. This is the function:
private boolean checkUsernameValidity(String enteredUsername) {
/**
* Create code for querying through firestore DB for enteredUsername
*/
final boolean[] usernameAvailable = {true};
String USERTAG = "User documents";
Log.d("Entered Username: ", enteredUsername);
DocumentReference userDocRef = users.document(enteredUsername);
userDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(USERTAG, "DocumentSnapshot data: " + document.getData());
Log.d("Warning", "Uh oh username is taken");
usernameAvailable[0] = false;
Toast.makeText(CreateAccount.this,
"This username is taken! Please enter a different username",
Toast.LENGTH_SHORT)
.show();
} else {
Log.d(USERTAG, "No such document, This Username is available");
}
} else {
Log.d(USERTAG, "get failed with ", task.getException());
}
}
});
/**
* If there was a user with entered username found already;
*/
if(!usernameAvailable[0]) {
return false;
}
if (enteredUsername.length() < 5) {
Toast.makeText(CreateAccount.this, "This username is too short",
Toast.LENGTH_SHORT)
.show();
return false;
}
Log.d("Status", "All Good!");
return true;
}
The function returns true according to the debugger before the usernameAvailable[0] is changed. Picture here:
In the picture, the Log of a successful status is printed before the log that says that the username was taken. I'm guessing that the function needs to be an asynchronous or something along those lines but I'm not 100% on creating asynchronous methods. How do I make it so that my function retrieves the document if it exists and sets my usernameAvailable[0] to false inside the get document function before going through the rest of the checkUsernameValidity method.
P.S.
usernameAvailable is a final array of booleans instead of just a boolean because it is accessed inside inner class
What you said is on the right track. The get() call you're making on the DocumentReference internally starts an asynchronous task which defers the network request to a background thread. If this wasn't the case then you would have a non-responsive app for the time it takes to receive the result. So instead of receiving the result synchoronously, in your code you attach an OnCompleteListener<*> which Firebase uses to call your onChanged method once the request is complete so that you can handle the result.
For a simple solution you can implement some sort of callback into checkUsernameValidity to process the result from wherever you are calling from. An implementation would look something like this:
interface Callback {
void onResult(boolean valid);
}
void checkUsernameValidity(Callback callback) {
userDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
callback.onResult(true);
}
});
}
I would recommend doing some research on asynchronicity and the basic concept of callbacks.

Save documentReference.getId() in a varible to use it in a different Statement [duplicate]

This question already has answers here:
How to return a DocumentSnapShot as a result of a method?
(2 answers)
Closed 3 years ago.
I new here, becuase I need some help with my code. I trying to make friend request in my app. In my case I want to save my requestid, which i just created in a string. I can do it and it works perfectly fine with documentReference.getId(). But now i want to use this ID in my second if-Statement as well, but it does not get there.
if (currentstate.equals("not_friends")) {
final Map<String, String> request = new HashMap<>();
request.put("yourid", yourid);
request.put("otherid", otherid);
request.put("Type", "req_send");
fStore.collection("request").add(request).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(otherProfile.this, "Versendet", Toast.LENGTH_SHORT).show();
currentstate = "req_send";
add.setEnabled(true);
add.setText("Anfrage löschen");
String requestid = documentReference.getId();
Toast.makeText(otherProfile.this, requestid, Toast.LENGTH_SHORT).show();
}
});
}
if (currentstate.equals("req_send")) {
fStore.collection("request").document(requestid).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(otherProfile.this, "Gelöscht", Toast.LENGTH_SHORT).show();
add.setText("Freundschaftsanfrage versenden");
currentstate = "not_friends";
add.setEnabled(true);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(otherProfile.this, "Nö", Toast.LENGTH_SHORT).show();
}
});
}
I add the data in the first If statement, but now the button changes and i want to delete the friend request in the second If Statement. So i want wo delete the data again in my Database. But the ID requestid does not save from the first statement, so I do not get acess the right data, which I wnt to delete.
Declare String requestid=null; outside the if statements i.e. global , then you will be able to access it in both the if blocks.Hope this works

Send number from NumberPicker to Firebase

Is there a way to send Number from NumberPicker to Firebase? I have connected a NumberPicker library from GITHUB. But I want when select number to send to Firebase, is there a way ?
I tried with this code :
String number = numberPicker.getText().toString().trim();
Code for Firebase:
private boolean updateProdus(String id, String number){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").child(id);
Produse produse = new Produse(id, number);
databaseReference.setValue(produse);
Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
return true;
}
But it's not working.
private boolean updateProdus(String id, String number){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").push();
databaseReference.child("number").setValue(number);
Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
return true;
}
Use push() to create a random id, then inside of it there will be a child that has the value number.
check this: https://developer.android.com/reference/android/widget/NumberPicker.html
you can get the number doing this:
String number=""+numberpicker.getValue();

Categories