android java to upload and retrieve picture from the firestore - java

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

Related

Cannot resolve method 'collection' in 'FirebaseStorage'

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

Social Network app: Profile photos don't appear correctly

I created a social network app using Java language with the ability to insert a picture as a profile photo. If I try to upload a photo of mine it works but if other users try to do it using another device they don't see my photo and I don't see theirs. Basically everyone sees their own photo using their own device.
However, despite uploading my profile photo properly, it tends to disappear after a period of time.
How to fix it?
Screenshot:
https://i.stack.imgur.com/SXo99.jpg
Code for try to setting profile photo:
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
if(task.getResult().exists()){
String name = task.getResult().getString("name");
String image = task.getResult().getString("image");
String about = task.getResult().getString("about");
String skills = task.getResult().getString("skills");
mainImageUri = Uri.parse(image);
setupName.setText(name);
setupAbout.setText(skills);
setupSkills.setText(about);
RequestOptions placeholderRequest = new RequestOptions();
placeholderRequest = placeholderRequest.placeholder(R.drawable.defaultuser);
Glide.with(getApplicationContext())
.setDefaultRequestOptions(placeholderRequest)
.load(image)
.into(setupImage);
}
} else {
String error = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "C'è stato un problema, riprova per favore.", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.INVISIBLE);
setupButton.setEnabled(true);
}
});
setupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String user_name = setupName.getText().toString();
final String about = setupAbout.getText().toString();
final String userSkills = setupSkills.getText().toString();
if (!TextUtils.isEmpty(user_name) && mainImageUri != null) {
progressBar.setVisibility(View.VISIBLE);
if (isChanged) {
user_id = firebaseAuth.getCurrentUser().getUid();
final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
image_path.putFile(mainImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
storeFirestore(task, user_name, about, userSkills, image_path);
} else {
Toast.makeText(SetupActivity.this, "C'è stato un problema, riprova per favore.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.INVISIBLE);
}
}
});
} else {
storeFirestore(null, user_name, about, userSkills, null);
}
} else {
if(TextUtils.isEmpty(user_name))
{
Toast.makeText(SetupActivity.this, "Per favore, inserisci un nickname!", Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(SetupActivity.this, "Per favore, inserisci una foto profilo!", Toast.LENGTH_LONG).show();
}
}
}
});
setupImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(SetupActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED) {
Snackbar snackbar = Snackbar.make(view, "Hai autorizzato l'app ad accedere al tuo archivio esterno?", Snackbar.LENGTH_SHORT);
snackbar.show();
ActivityCompat.requestPermissions(SetupActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
BringImagePicker();
}
} else {
BringImagePicker();
}
}
});
}
private void storeFirestore(Task<UploadTask.TaskSnapshot> task, String user_name,
String userSkills, String about, StorageReference image_path){
Uri download_uri = null;
if(task != null) {
task.getResult().getStorage().getDownloadUrl();
} else {
download_uri = mainImageUri;
}
Map<String, String> userMap = new HashMap<>();
userMap.put("skills", userSkills);
userMap.put("name", user_name);
userMap.put("about", about);
userMap.put("image", download_uri.toString());
userMap.put("user_id", user_id);
firebaseFirestore.collection("Users").document(user_id).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SetupActivity.this, "Le impostazioni sono state aggiornate!", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(SetupActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
} else {
Toast.makeText(SetupActivity.this, "C'è stato un problema, riprova per favore.", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.INVISIBLE);
}
});
}
In the first line "user_id" is "firebaseAuth.getCurrentUser().getUid();"
Code for onActivityResult:
https://i.stack.imgur.com/BTRJv.png
This looks wrong:
Uri download_uri = null;
if(task != null) {
task.getResult().getStorage().getDownloadUrl();
} else {
download_uri = mainImageUri;
}
I recommend studying the documentation on getting a download URL (or here), as that really is the one and only way to get a download URL.
In your case, that'd be something like this:
private void storeFirestore(Task<UploadTask.TaskSnapshot> task, String user_name,
String userSkills, String about, StorageReference image_path){
image_path.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri download_uri) {
Map<String, String> userMap = new HashMap<>();
userMap.put("skills", userSkills);
userMap.put("name", user_name);
userMap.put("about", about);
userMap.put("image", download_uri.toString());
userMap.put("user_id", user_id);
firebaseFirestore.collection("Users").document(user_id).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SetupActivity.this, "Le impostazioni sono state aggiornate!", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(SetupActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
} else {
Toast.makeText(SetupActivity.this, "C'è stato un problema, riprova per favore.", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.INVISIBLE);
}
});
}
});
}
As per the documentation you'll need to use the onSuccessListener to ensure that the download URL is actually filled and ready to be used.
I see that you call the storeFirestore function two times, with the one on line 79 with the image_path parameter with null value. That's probably the cause of the crash you mentioned in the comments above.
You can try with something like this:
private void storeFirestore(Task<UploadTask.TaskSnapshot> task, String user_name,
String userSkills, String about, StorageReference image_path){
Uri download_uri = null;
if (image_path != null) {
download_uri = image_path.getDownloadUrl();
}
else if(task != null) {
download_uri = task.getResult().getStorage().getDownloadUrl();
} else {
download_uri = mainImageUri;
}
download_uri.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloaded_uri) {
Map<String, String> userMap = new HashMap<>();
userMap.put("skills", userSkills);
userMap.put("name", user_name);
userMap.put("about", about);
userMap.put("image", downloaded_uri.toString());
userMap.put("user_id", user_id);
firebaseFirestore.collection("Users").document(user_id).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SetupActivity.this, "Le impostazioni sono state aggiornate!", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(SetupActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
} else {
Toast.makeText(SetupActivity.this, "C'è stato un problema, riprova per favore.", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.INVISIBLE);
}
});
}
});
}

Android Firebase How to wait for image upload before registering to database?

I am new to android development and I have an issue.
I have a fragment in which a user can post an announcement and should be able to upload a photo(optional).
When the form is full and the "Post announcement" button is pressed, I trigger the method to save the information to the database.
The only problem I am facing is retrieving the Uri of the newly uploaded photo.
This is the code which extracts the information.
public Map<String, Object> appendDataFromAnnouncementForm(){
String title = titleLineEdit.getText().toString();
String category = categoryLineEdit.getText().toString();
String description = descriptionLineEdit.getText().toString();
String date = dateLineEdit.getText().toString();
String time = timeLineEdit.getText().toString();
String location = locationLineEdit.getText().toString();
//Image upload to firebase + getting the Uri
if(localPhotoUri != null){
uploadImageToFirebase(generatePhotoName(localPhotoUri), localPhotoUri);
}
Map<String, Object> newAnnouncement = new HashMap<>();
//#####################################################
if(uploadedImageUri != null) // <- this is always null
{newAnnouncement.put("imageUri", uploadedImageUri.toString());}
//#############################################################
newAnnouncement.put("title", title);
newAnnouncement.put("category", category);
newAnnouncement.put("description", description);
newAnnouncement.put("date", date);
newAnnouncement.put("time", time);
newAnnouncement.put("location", location);
return newAnnouncement;
}
Below I am posting the code which uploads the photo to Firebase Storage. Since
private void uploadImageToFirebase(String photoName, Uri localContentUri) {
imagesStorageReferance = myStorageReference.child("images/" + photoName);
imagesStorageReferance.putFile(localContentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//getUploadedImageUri(referenceToImageFolder);
imagesStorageReferance.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: The download url of the photo is "
+ uri.toString());
uploadedImageUri = uri; /// <- I want to retrieve this
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Failed uploading the photo to the database " + e.getMessage());
}
});
}
From what I have read on the Internet, this is an synchronization problem(basically, the app registers the information to the database before my photo is uploaded). There are many solutions which I have tried, but I can't really figure it out one to work on my case...
I would be very grateful if you could provide me some explanation on what I should do in order to fix this. How can I wait the photo to be uploaded ?
I am sharing the code from my project:
Assign this globally:
StorageTask uploadTask;
String myUrl = "";
and this is code:
private void uploadImage()
{
if (imageUri != null)
{
final StorageReference reference = storageReference.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask = reference.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isComplete())
{
throw task.getException();
}
return reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful())
{
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Categories")
.child(randomKey);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("categoryId", randomKey);
hashMap.put("categoryImage", myUrl);
hashMap.put("categoryName", editText.getText().toString());
databaseReference.setValue(hashMap);
save.setVisibility(View.VISIBLE);
startActivity(new Intent(AddCategoryActivity.this, CategoriesActivity.class));
}
else
{
save.setVisibility(View.VISIBLE);
Toast.makeText(AddCategoryActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
save.setVisibility(View.VISIBLE);
Toast.makeText(AddCategoryActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else
{
save.setVisibility(View.VISIBLE);
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
Since firebase works asynchronously, the code continues to execute regardless of whether firebase has finished the upload process or not. In your case, the time to run the code following firebase is faster than the upload time to firebase to eventually assign uploadedImageUri = uri; which explains why you are getting a null value for uploadedImageUri present directly after the call for upload.
For this matter, I would suggest you to register to database inside uploadImageToFirebase function after uploadedImageUri = uri; to ensure that uploadedImageUri is never null and always fetched before database registration.
private void uploadImageToFirebase(String photoName, Uri localContentUri) {
imagesStorageReferance = myStorageReference.child("images/" + photoName);
imagesStorageReferance.putFile(localContentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//getUploadedImageUri(referenceToImageFolder);
imagesStorageReferance.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: The download url of the photo is "
+ uri.toString());
uploadedImageUri = uri;
String title = titleLineEdit.getText().toString();
String category = categoryLineEdit.getText().toString();
String description = descriptionLineEdit.getText().toString();
String date = dateLineEdit.getText().toString();
String time = timeLineEdit.getText().toString();
String location = locationLineEdit.getText().toString();
Map<String, Object> newAnnouncement = new HashMap<>();
newAnnouncement.put("imageUri", uploadedImageUri.toString());
newAnnouncement.put("title", title);
newAnnouncement.put("category", category);
newAnnouncement.put("description", description);
newAnnouncement.put("date", date);
newAnnouncement.put("time", time);
newAnnouncement.put("location", location);
//UPLOAD newAnouncement TO FIREBASE HERE...
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Failed uploading the photo to the database " + e.getMessage());
}
});
}

Wait for a method completed first, before continue running

I'm trying to run a method called uploadProfilePhoto() but the code after this method invocation runs first even though uploadProfilePhoto() has not finish running. Is there anyway i can let uploadProfilePhoto() finish it's process first before continuing?
I tried using AsynTask but it still doesn't work. Seems like it is because doInBackground() is for a series of code, not method.
AsyncTask
protected class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
uploadProfilePhoto();
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(ProfileSetup.this, "Account created successfully.", Toast.LENGTH_SHORT).show();
mAuth.signInWithEmailAndPassword(email, password);
startActivity(new Intent(ProfileSetup.this, MainActivity.class));
}
}
uploadProfilePhoto()
private void uploadProfilePhoto() {
if (mImageUri != null) {
final StorageReference imageReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
storageTask = imageReference.putFile(mImageUri);
storageTask.continueWithTask(new Continuation() {
#Override
public Task<Uri> then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return imageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
String myid = getIntent().getStringExtra("uid");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(myid);
reference.child("profilePicUrl").setValue(myUrl);
finish();
} else {
Toast.makeText(ProfileSetup.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileSetup.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show();
}
}
I can think of two ways
storageTask = imageReference.putFile(mImageUri);
storageTask.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
myUrl = task.getResult().toString();
String myid = getIntent().getStringExtra("uid");
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference("Users").child(myid);
reference.child("profilePicUrl").setValue(myUrl);
startActivity(new Intent(ProfileSetup.this, MainActivity.class));
finish();
} else {
Toast.makeText(ProfileSetup.this, "Failed",
Toast.LENGTH_SHORT).show();
}
}
2nd way which is not very clean and nice actually should be considered as a bad practice , but knowing alternative way is no harm so
you can start MainActivity Imidiately after saying imageReference.putFlie(mImageUri);
imgeReference.putFile(mImageUri);
startActivity(new Intent(ProfileSetup.this, MainActivity.class));
Now in the MainActivity
while(ProfileSetup.getImageUrl() == null){ // define a method to return the url
Systemclock.sleep(500); // if it is small image you can hote it will be uplaoded in seconds
}
Picasso.with(this).load(ProfileSetup.getImageUrl()).fit().into(imageView); // the while loop terminates when your image gets uploaded because getImageUrl() did not return null , now you know image is there you can download and set it to imageView by using Piccaso
With this approach you don't need a completeListener but i don't recommend doing it because it is more complex and doesn't deal with any failure of imageUploading

Unable to put image url to Firestore database after uploading the image to firebase storage

I'm trying to upload some images to firestore storage and put the image URL to firebase database. The images are uploading successfully but the image URLs aren't being added to the database. The problem that I think might be causing this is that the image URL is being added to the Hashmap after uploading the image but the database upload process isn't waiting for the URL instead, adding all other HashMap keys to the database before the Upload task returns the URL. This way all other keys get added to the database but not the Image URLs. In the below code product id is being added successfully to the database, also if I leave any image unselected its url alse gets added as empty to the database which is working fine but if I select an image to upload, The hashmap to database upload finishes even before getting the uploaded image URL.
public class AddProductDataActivity extends AppCompatActivity {
String productId;
EditText productIdEditText;
ImageView addProductImage3;
Button addProductSubmit;
final int IMAGE3_REQUEST = 30;
Uri image3LocationPath;
StorageReference objectStorageReference;
FirebaseFirestore objectFireBaseFireStore;
Map<String, String> objectMap = new HashMap<>();
StorageReference img3Store;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product_data);
brandNameEditText =(EditText)
addProductImage3 = (ImageView) findViewById(R.id.add_product_image3);
objectStorageReference =
FirebaseStorage.getInstance().getReference("images");
objectFireBaseFireStore = FirebaseFirestore.getInstance();
addProductImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent objectIntent = new Intent();
objectIntent.setType("image/*");
objectIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(objectIntent, IMAGE3_REQUEST);
}
});
addProductSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productId = productIdEditText.getText().toString();
if(image3LocationPath != null)
{
final String image3Name = productId + "_image3." + getExtension(image3LocationPath);
img3Store = objectStorageReference.child(image3Name);
UploadTask imageUploadTask = img3Store.putFile(image3LocationPath);
imageUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if(!task.isSuccessful())
{
Toast.makeText(AddProductDataActivity.this, "Task Unsuccessful", Toast.LENGTH_SHORT).show();
}
return img3Store.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful())
{
String image_3_url = task.getResult().toString();
objectMap.put("image3_url",image_3_url);
}
else
{
Toast.makeText(AddProductDataActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
objectMap.put("image3_url","");
}
objectFireBaseFireStore.collection("images").document(productId).set(objectMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(AddProductDataActivity.this, "Product Added Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddProductDataActivity.this, "Error in Adding Product. Please Try Again.\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 30:
try
{
if(resultCode == RESULT_OK && data != null && data.getData() != null)
{
image3LocationPath = data.getData();
Bitmap objectBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image3LocationPath);
addProductImage3.setImageBitmap(objectBitmap);
}
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
private String getExtension(Uri uri){
try
{
ContentResolver objectContentResolver = getContentResolver();
MimeTypeMap objectMimeTypeMap = MimeTypeMap.getSingleton();
return objectMimeTypeMap.getExtensionFromMimeType(objectContentResolver.getType(uri));
}
catch (Exception e)
{
Toast.makeText(AddProductDataActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
Your code
objectFireBaseFireStore.collection("images").document(productId).set(objectMap)
executes before
objectMap.put("image3_url",image_3_url)
Which means when you are setting your url, your objectMap does not have the key image3_url
Try to set values to database inside onComplete() or use different workaround to set only the url.
You forgot to add your HashMap to Database Reference of Firebase.
This is reference from my current project code.
private void uploadVideo() {
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference riversRef = mStorageRef.child(Constants.STORAGE_PATH + "/" + mFinalUploadUri.getLastPathSegment());
riversRef.putFile(mFinalUploadUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return riversRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseFirestore database = FirebaseFirestore.getInstance();
String mSelectedCategory = binding.categorySpinner.getSelectedItem().toString();
DocumentReference newDocumentReference = database.collection(PENDING_PATH).document();
VideoModel videoModel = new VideoModel();
videoModel.setDocumentId(newDocumentReference.getId());
videoModel.setTitle(mTitle);
videoModel.setCategory(mSelectedCategory);
//videoModel.setTime(FieldValue.serverTimestamp());
videoModel.setUrl(downloadUri != null ? downloadUri.toString() : null);
newDocumentReference.set(videoModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
binding.progressBar.setVisibility(View.GONE);
binding.button.setVisibility(View.VISIBLE);
binding.videoView.setVisibility(View.GONE);
selectedUri = null;
Toast.makeText(AdminVideoUploadActivity.this, R.string.uploaded_successfully, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AdminVideoUploadActivity.this, R.string.failed_to_upload, Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
Now you can check code and find where you have done mistake. Just add lines of code of inserting in database.
Thank you.

Categories

Resources