i want to accsess my firebase collection but somehow it didnt work on this java file, in otherwise i had another java file on my android project thats containts the same syntax and its actually work.. i dont have any idea to solve this line
on Signupn.java (worked)
fAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUp.this, "User Created", Toast.LENGTH_SHORT).show();
userId = fAuth.getCurrentUser().getUid();
DocumentReference documentReference =fStore.collection("users").document(userId);
Map<String,Object> user =new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phone);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d(TAG,"onSuccess: user Profile is created for "+ userId);
}
});
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
Toast.makeText(SignUp.this, "Error!"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
on EditProfile.java (error)
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editFullName.getText().toString().isEmpty() || editEmail.getText().toString().isEmpty()
|| editPhone.getText().toString().isEmpty()) {
Toast.makeText(EditProfile.this, "All Fields Are Required.", Toast.LENGTH_SHORT).show();
return;
}
String email = editEmail.getText().toString();
user.updateEmail(email).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
DocumentReference docRef = fStore.collection("users").document(user.getUid());
Map<String, Object> edited = new HashMap<>();
edited.put("email", email);
edited.put("fName", editFullName.getText().toString());
edited.put("phone", editPhone.getText().toString());
docRef.update(edited);
Toast.makeText(EditProfile.this, "Email Changed Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditProfile.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
});
here is where the error line
DocumentReference docRef = fStore.collection("users").document(user.getUid());
in collection sentence.
this picture from editProfile.java
this picture from signup.java
thank you for your value answers, any answer i really apriciate it.
Please verify your dataStype for fstore object in both classes or post full code wherever you are declaring the fstore and intializing it
Related
This is all the code with register account with email password, save verify email, save user data into Firestore database. Only the Firestore database can't run.
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// send verification link
FirebaseUser fuser = fAuth.getCurrentUser();
fuser.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(register.this, "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Email not sent " + e.getMessage());
}
});
Toast.makeText(register.this, "User Created.", Toast.LENGTH_SHORT).show();
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phone);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "onFailure: " + e.toString());
}
});
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
else {
Toast.makeText(register.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
The Firebase authentication operation is asynchronous. This means that you can be sure that authentication succeeded only when the onSuccess() method fires. Since you say that the authentication process successfully completes, your first onSuccess() is triggered. Your second onSuccess() is not triggered because the code that corresponds to the addition of data to Firestore is outside the callback, hence that behavior. To solve this, all the code that exists outside the callback should be moved inside the first onSuccess() as explained in the following line of code:
fAuth
.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// send verification link
FirebaseUser fuser = fAuth.getCurrentUser();
fuser.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(register.this, "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
Toast.makeText(register.this, "User Created.", Toast.LENGTH_SHORT).show();
//Moved code 👈👈👈
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phone);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "onFailure: " + e.toString());
}
});
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Email not sent " + e.getMessage());
}
});
} else {
Toast.makeText(register.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
In this way, you be able to write the data to Firestore when the authentication process is completed.
I'm trying to get pictures from firebase storage and save it into the firestore.
I upload the picture once, and then I tried to open this app but it keeps stop.
java.lang.IllegalArgumentException: uri cannot be null
It shows this error.
Here is my code, and this is the part occurring error.
private void postButtonClicked(){
//immutable read-only variable
final String title = ((EditText)findViewById(R.id.titleEditText)).getText().toString();
final String contents = ((EditText)findViewById(R.id.contentsEditText)).getText().toString();
if(!title.trim().isEmpty() || !contents.trim().isEmpty()){
final StorageReference postRef = storageReference.child("post_images").child(FieldValue.serverTimestamp().toString()+".jpg");
postRef.putFile(postImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
postRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
HashMap<String, Object> writeinfoMap = new HashMap<>();
writeinfoMap.put("image", uri.toString());
writeinfoMap.put("title", title);
writeinfoMap.put("contents", contents);
writeinfoMap.put("time", FieldValue.serverTimestamp());
// postMap.put("user", user);
firestore.collection("post").add(writeinfoMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if(task.isSuccessful()){
startActivity(new Intent(WritePostActivity.this, MainActivity.class));
Toast.makeText(WritePostActivity.this, "posted!", Toast.LENGTH_SHORT).show();
finish();
}else{
String error = task.getException().getMessage();
Toast.makeText(WritePostActivity.this,"Error: "+error,Toast.LENGTH_SHORT).show();
}
}
});
}
});
}else{
String error = task.getException().getMessage();
Toast.makeText(WritePostActivity.this,"Error: "+error,Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(this,"please enter the title.", Toast.LENGTH_SHORT).show();
}
}
please help me to find out the error and fix it. Thanks
I am trying to update my email from FireBase, how can I achive this? updateEmail looks like has been depreacated?
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
AuthCredential credential= EmailAuthProvider.getCredential(user.getEmail(),edtPassword.getText().toString());
user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(edtEmail.getText().toString())
.addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size()==0){
Here--------------------------------->
}else {
Toast.makeText(AccountSettingsActivity.this,"The Email is alread in use",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(AccountSettingsActivity.this,"Task is not successfull in fetch",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AccountSettingsActivity.this,"Unable to edt email",Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(AccountSettingsActivity.this,"Task is not successfull", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AccountSettingsActivity.this,"Unable to update email failure",Toast.LENGTH_LONG).show();
}
});
}
I had the same issu and I found the solution here : How to update email from Firebase in Android?
To retrieve password for credential you can use SharedPreferences.
It worked for me ;)
I have uploaded 1 Hashmap to firestore.And when i try to upload one more Hashmap to the same document it replaces my previous Hashmap.Why is it so?
I change the String title everytime and still it replaces the previous Hashmap.
String poll1 = Poll1.getText().toString().trim();
String poll2 = Poll2.getText().toString().trim();
String poll3 = Poll3.getText().toString().trim();
String title = Title.getText().toString().trim();
DocumentReference documentReference = firestore.collection("Polls").document("abc1");
Map<String, Object> nestedData = new HashMap<>();
nestedData.put(poll1 , 0 );
nestedData.put(poll2 , 0);
nestedData.put(poll3 , 0);
Map<String, Object> upload = new HashMap<>();
upload.put(title, nestedData);
documentReference.set(upload).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});
your document needs to mention that this has to be merged instead replace.
.set(data, SetOptions.merge())
Try this if it works.
documentReference.set(upload, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(polls.this, "UPLOADED", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(polls.this, "FAILED", Toast.LENGTH_LONG).show();
}
});
The problem I am facing is: when user 2 tries to access the same database collection, instead of showing that some data already exists in the database(the requirement is that data entered by the user 1 is saved in that same database), I get null in database. I could also figure out why it happened but clueless about how to query the firestore collection in such a way that different users save unique values for document fields "StartTime" and "EndTimes" in BookingInformation collection?
Following is the code I used;
FirebaseAuth fAuth = FirebaseAuth.getInstance();
String userId = fAuth.getCurrentUser().getUid();
Log.d(TAG,"userID: "+userId);
FirebaseFirestore fstore = FirebaseFirestore.getInstance();
DocumentReference docRef =
fstore.collection("BookingInformation").document(userId);
It happened that way because I have used userId as the document id of "BookingInformation" collection. By doing so, every time a new user login a new document is created. How should I solve it to make sure that when user 2 enters data it first checks that some document exists in the collection?
Edited:
Added code
NewBookingFragment.java
newBookingViewModel.getBookingInformation().observe(getViewLifecycleOwner(), new Observer<BookingInfo>() {
#Override
public void onChanged(final BookingInfo bookingInfo) {
Log.d(TAG,"hi from bookingInfodatabase");
Log.d(TAG,"content of bookingInfodatabase"+bookingInfo);
if (bookingInfo == null) {
Log.d(TAG,"no data from database, so add as a new");
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "No data from database, so add as a new booking information", Toast.LENGTH_SHORT);
toast.show();
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toast1 = Toast.makeText(getActivity().getApplicationContext(), "No data in database to compare!", Toast.LENGTH_SHORT);
toast1.show();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
final Map<String, Object> reserveInfo = new HashMap<>();
reserveInfo.put("Date",date.getText().toString());
reserveInfo.put("StartTime",startTime.getText().toString());
reserveInfo.put("EndTime",endTime.getText().toString());
reserveInfo.put("UserId",currentUserId);
dataStore.collection("BookingInformation").document(currentUserId).set(reserveInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(), "Area reserved successfully", Toast.LENGTH_SHORT);
toast4.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast5 = Toast.makeText(getActivity().getApplicationContext(), "Reservation failed", Toast.LENGTH_SHORT);
toast5.show();
}
});
}
});
}else{
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"after clicking available button");
Log.d(TAG,"booking id"+bookingInfo.getBookingDocId());
Log.d(TAG,"database time: "+bookingInfo.getStartTime());
Log.d(TAG,"user input time: "+startTime.getText().toString());
Log.d(TAG,"comparing time: "+bookingInfo.getStartTime().equals(startTime.getText().toString()));
if (bookingInfo.getDate().equals(date.getText().toString()) ){
Log.d(TAG, "Date check ");
if (bookingInfo.getStartTime().equals(startTime.getText().toString()) && bookingInfo.getEndTime().equals(endTime.getText().toString())) {
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Select another time.", Toast.LENGTH_SHORT);
toast.show();
Log.d(TAG, "start and end time check ");
if (bookingInfo.getStartTime().equals(startTime.getText().toString())) {
Log.d(TAG, "start time check ");
if (bookingInfo.getEndTime().equals(endTime.getText().toString())) {
Toast toast2 = Toast.makeText(getActivity().getApplicationContext(), "Select another end time.", Toast.LENGTH_SHORT);
toast2.show();
Log.d(TAG, "end time check ");
}
Log.d(TAG, "end time not equal check ");
}
Log.d(TAG, "start time not equal check ");
}
else{
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(), "Area available at this time,'Book' it.", Toast.LENGTH_SHORT);
toast4.show();
availabletextView.setText("Area available");
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
final Map<String, Object> reserveInfo = new HashMap<>();
reserveInfo.put("Date",date.getText().toString());
reserveInfo.put("StartTime",startTime.getText().toString());
reserveInfo.put("EndTime",endTime.getText().toString());
reserveInfo.put("UserId",currentUserId);
dataStore.collection("BookingInformation").document(currentUserId).set(reserveInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(), "Area reserved successfully", Toast.LENGTH_SHORT);
toast4.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast5 = Toast.makeText(getActivity().getApplicationContext(), "Reservation failed", Toast.LENGTH_SHORT);
toast5.show();
}
});
}
});
}
} else {
availabletextView.setText("Area available");
Log.d(TAG, "user id: "+currentUserId);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "user id in fragment class: "+currentUserId);
final Map<String, Object> reserveInfo = new HashMap<>();
reserveInfo.put("Date",date.getText().toString());
reserveInfo.put("StartTime",startTime.getText().toString());
reserveInfo.put("EndTime",endTime.getText().toString());
reserveInfo.put("UserId",currentUserId);
dataStore.collection("BookingInformation").document(currentUserId).set(reserveInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(), "Area reserved successfully", Toast.LENGTH_SHORT);
toast4.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast5 = Toast.makeText(getActivity().getApplicationContext(), "Reservation failed", Toast.LENGTH_SHORT);
toast5.show();
}
});
}
});
}
}
});
}
}
});
NewBookingViewModel.java
public class NewBookingViewModel extends ViewModel {
private static final String TAG = "Firelog";
public LiveData<BookingInfo> getBookingInformation() {
final MutableLiveData<BookingInfo> bookingInfoMutableLiveData = new MutableLiveData<>();
FirebaseAuth fAuth = FirebaseAuth.getInstance();
String userId = fAuth.getCurrentUser().getUid();
Log.d(TAG,"userID: "+userId);
FirebaseFirestore fstore = FirebaseFirestore.getInstance();
DocumentReference docRef = fstore.collection("BookingInformation").document(userId);
Log.d(TAG,"docRef"+docRef);
String docid = docRef.getId();
Log.d(TAG,"document id"+docid);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
Log.d(TAG,"hi from viewmodel database");
DocumentSnapshot documentSnapshot = task.getResult();
Log.d(TAG, "Doc ID: "+documentSnapshot.getId());
Log.d(TAG,"document exist: "+documentSnapshot.exists());
if (documentSnapshot != null && documentSnapshot.exists()) {
String date = documentSnapshot.getString("Date");
String startTime = documentSnapshot.getString("StartTime");
String endTime = documentSnapshot.getString("EndTime");
BookingInfo bookingInfo = documentSnapshot.toObject(BookingInfo.class);
Log.d(TAG,"hi from viewmodel date: "+date);
bookingInfo.setDate(date);
bookingInfo.setStartTime(startTime);
bookingInfo.setEndTime(endTime);
bookingInfoMutableLiveData.postValue(bookingInfo);
} else {
bookingInfoMutableLiveData.postValue(null);
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
}
});
return bookingInfoMutableLiveData;
}
}
Thanks.
I just figured out that to allow 2 or more users to enter and save data in the collection without any duplicate data w.r.t startTime and endTime field, I have to make sure that the document already exists or not. For that, as a solution, I counted the document in the collection.
Following is the code "NewBookingViewModel.java"
fstore.collection("BookingInformation")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
if (!querySnapshot.isEmpty()) {
for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {
count++;
Log.d(TAG, "document count: "+count);
if (count != 0) {
String date = queryDocumentSnapshot.getString("Date");
String startTime = queryDocumentSnapshot.getString("StartTime");
String endTime = queryDocumentSnapshot.getString("EndTime");
BookingInfo bookingInfo = queryDocumentSnapshot.toObject(BookingInfo.class);
bookingInfo.setBookingDocId((queryDocumentSnapshot.getId()));
bookingInfo.setDate(date);
bookingInfo.setStartTime(startTime);
bookingInfo.setEndTime(endTime);
bookingInfoMutableLiveData.postValue(bookingInfo);
}else {
Log.d(TAG, "No booking data");
}
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
} else {
bookingInfoMutableLiveData.postValue(null);
}
}
});