I want to upload image list in firebase but in the firebase upload success listener doesn't add image list on OnSuccessListener.
Tried
I add string value outside of the add onSuccessListener class it works and i tried to log the url it works too.But it doesn't add the string value in the arrayList in the OnSuccessListener.
Thank you for the help.
Main code
public void UploadImage() {
if (isUserSelected != null) {
progressDialog.setTitle("Image is Uploading...");
Log.d(TAG, "UploadImage: uploading");
progressDialog.show();
Log.d(TAG, "UploadImage: after progress bar");
for (int i = 0; i < multipleFileUploads.size(); i++) {
Log.d(TAG, "UploadImage: " + i);
final StorageReference storageReference2 = storageReference.child(System.currentTimeMillis() + "." + GetFileExtension(multipleFileUploads.get(i)));
storageReference2.putFile(multipleFileUploads.get(i))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onSuccess: ");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
storageReference2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri " + uri.toString());
imagelist.add(uri.toString());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onProgress: " + taskSnapshot.getBytesTransferred());
Log.d(TAG, "onProgress: " + taskSnapshot.getTotalByteCount());
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Log.d(TAG, "onComplete: " + task.getException());
}
});
}
imageList.add("custom list");
uploadinfo imageUploadInfo = new uploadinfo(txtdata.getText().toString(), txtData1.getText().toString(), imageList.toString());
String ImageUploadId = databaseReference.push().getKey();
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
} else {
Toast.makeText(uploadimg1.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
POJO Code for Firebase
public class uploadinfo {
public String imageName;
public String imageName1;
public String imageListString;
public uploadinfo(String imageName, String imageName1, String imageListString) {
this.imageName = imageName;
this.imageName1 = imageName1;
this.imageListString = imageListString;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageName1() {
return imageName1;
}
public void setImageName1(String imageName1) {
this.imageName1 = imageName1;
}
public String getImageListString() {
return imageListString;
}
public void setImageListString(String imageListString) {
this.imageListString = imageListString;
}
}
In Firebase
The problem might be in your model. In firebase the order goes imageListString, imageName, imageName1. But in model in constructor you got String imageName, String imageName1, String imageListString. At the same time im not sure how you generate the list which you create BEFORE send it to Firebase.
You can try this method
UploadTask uploadTask = storageReference2.putFile(multipleFileUploads.get(i));
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
imagelist.add(downloadUri.toString());
} else {
// Handle failures
// ...
}
}
});
Related
I'm facing a problem with storing the image url into real-time database.
It stores a url which is not related to the url of the image in the storage.
private void uploadFile (){
if (mImageUri != null){
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
uploadProgressBar.setVisibility(View.VISIBLE);
uploadProgressBar.setIndeterminate(true);
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
uploadProgressBar.setVisibility(View.VISIBLE);
uploadProgressBar.setIndeterminate(false);
uploadProgressBar.setProgress(0);
}
},500);
Toast.makeText(AddProductActivity.this, "Product is added successfully!", Toast.LENGTH_SHORT).show();
Product product = new Product(productName.getText().toString()
,productDescription.getText().toString()
,price.getText().toString()
,taskSnapshot.getUploadSessionUri().toString()
,oldPrice.getText().toString()
, quantity.getText().toString());
String uploadID = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadID).setValue(product);
uploadProgressBar.setVisibility(View.INVISIBLE);
openMainActivity();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
uploadProgressBar.setVisibility(View.INVISIBLE);
Toast.makeText(AddProductActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 *taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
uploadProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "You haven't Selected any file", Toast.LENGTH_SHORT).show();
}
}
When I copy the stored url from the imageUrl field and try to see if it will display the image, i get this text error :
Invalid request. X-Goog-Upload-Command header is missing.
You need to change taskSnapshot.getUploadSessionUri().toString() while uploading image to the right uri as below
Below is the sample to get the right URI
firebaseStorageReference.putFile(resultUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String mDownloadUri = uri.toString();
}
});
}
});
and to apply that in your code
private void uploadFile (){
if (mImageUri != null){
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
uploadProgressBar.setVisibility(View.VISIBLE);
uploadProgressBar.setIndeterminate(true);
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
uploadProgressBar.setVisibility(View.VISIBLE);
uploadProgressBar.setIndeterminate(false);
uploadProgressBar.setProgress(0);
}
},500);
final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadUri = uri.toString();
Toast.makeText(AddProductActivity.this, "Product is added successfully!", Toast.LENGTH_SHORT).show();
Product product = new Product(productName.getText().toString()
,productDescription.getText().toString()
,price.getText().toString()
,downloadUri
,oldPrice.getText().toString()
, quantity.getText().toString());
String uploadID = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadID).setValue(product);
uploadProgressBar.setVisibility(View.INVISIBLE);
openMainActivity();
}
});
// rest of your code
Hope it helps, and I am welcome for further support
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.
I am using Firebase upload and I want to write the uploaded method in a class out of the activity as I want to use it several times and at the same time I want to use ProgressBar that shows the progress and as it is known we can't use findViewById out of activity or Fragment.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getError();
float progress = (float) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
System.out.println("Upload is " + progress + "% done");
**Here I wanna use a progressBar**
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
int errorCode = ((StorageException) exception).getErrorCode();
String errorMessage = exception.getMessage();
// test the errorCode and errorMessage, and handle accordingly
Log.d(TAG, "onSuccess: The photo has NOT been uploaded" + errorCode + errorMessage);
Toast.makeText(mContext, "Sorry the photo has not been uploaded .. Please Try again", Toast.LENGTH_SHORT);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
circleProgressBar.setVisibility(View.GONE);
Log.d(TAG, "onSuccess: The photo is being uploaded");
Toast.makeText(mContext, "The photo has been uploaded successfully", Toast.LENGTH_SHORT).show();
//
}
}).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if (downloadUri != null){
String photoStringUrl = downloadUri.toString();
Log.d(TAG, "onComplete: Upload " + photoStringUrl);
//Inserting the profile photo into database {user_profile_account}
firebaseUtilities.saveProfilePhotoToDatabase(photoStringUrl);
}
}
You can pass Activity as a parameter instead of Context.
I am trying to upload a custom object to Firebase Firestore, but the Firestore object should contain a download image url. The idea I have to do this is to upload the image first wait for that to complete, get a reference to the download url, update my custom class, then upload this to Firestore. I would then want to notify my view when this last upload(upload to Firestore) is completed. I was thinking of doing this by returning a task. Here is what I have for upload image:
ref.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//use uri to update object and then upload to firestore
mObject.setImageUri(uri)
uploadToFirestore(myObject);
}
Log.d(TAG, "onSuccess: uri= "+ uri.toString());
}
});
}
});`
I am not sure how to return the final task of Firstore upload as it is done within the task of image upload. My goal is to listen for when the uploadToFireStore() is completed and then inform my view. Any suggestions would be appreciated. Thanks!
Edit: I have structure like so-
View has gets info from user passes it to viewmodel as a custom object. View model then calls db to perform upload.
my idea is to return a task from db to viewmodel which will return said task to view. View checks for completion and then stops loader. Is this a good way to think about this?
My working example.
public class SomeClass {
private String downloadUrl;
private final FirebaseStorage storage = FirebaseStorage.getInstance();
private int count = 0;
public interface Callback {
void callingBack();
void getReady();
}
public int getCount() {
return count;
}
private Callback callback;
public void registerCallBack(Callback callback) {
this.callback = callback;
}
public String getImageUri () {
return downloadUrl;
}
public void uploadImage (String srcPath, String fileName, Context context, int size) {
StorageReference storageRef = storage.getReference();
StorageReference imageRef = storageRef.child(fileName);
try {
InputStream inputStream = new FileInputStream(new File(srcPath));
imageRef.putStream(inputStream)
.continueWithTask(task -> imageRef.getDownloadUrl())
.addOnCompleteListener(task -> {
downloadUrl = task.getResult().toString();
callback.callingBack();
this.count++;
if (this.count == size) {
callback.getReady();
this.count = 0;
}
});
} catch (Exception e) {
Toast.makeText(context, "Connection error", Toast.LENGTH_LONG).show();
}
}
}
Activity Code
public void someMehtod() {
String fileName;
String filePath;
int size = YOUR_SIZE;
String[] imgUrlList = new String[size];
for (int i = 0; i < size; i++) {
fileName = "img_" + i + ".jpg"; // set target file name
filePath = "/storage/emulated/0/Download/images_" + i + ".jpg"; // for example (u need get your real source file paths)
getImageUri.registerCallBack(new GetImageUri.Callback() {
#Override
public void callingBack() {
imgUrlList [getImageUri.getCount()] = getImageUri.getImageUri();
}
}
#Override
public void getReady() {
// here u can use your URLs
for (int k = 0; k < size; k ++) {
Log.d(TAG, "getReady: " + imgUrlList [k]);
}
});
getImageUri.uploadImage(filePath, fileName, this.getContext(), imgListCount);
}
}
I figured out how to solve the issue. Using callbacks. Create an interface like so
public interface Callback {
void result(Result result);
void url(Uri downloadUrl);
}
Note: result is an enum class with two values FAILED and SUCCESS
Then in your view call the view model like so
ViewModel.saveoBJECT(mObject, new Callback() {
#Override
public void result(Result result) {
switch (result){
case SUCCESS:
mProgressbar.setVisibility(View.GONE);
break;
case FAILED:
Log.v(TAG, "Failed");
Toast.makeText(getApplicationContext(), "OOPS ERROR!", Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void url(Uri downloadUrl) { }
});
and in your db do do something like this
uploadImage(Uri.parse(imageString), prepend, new Callback() {
#Override
public void result(Result result) {}
#Override
public void uri(Uri downloadUrl) {
saveObjectInDB(downloadUrl, new Callback() {
#Override
public void result(Result result) {
callback.result(result);
}
#Override
public void url(Uri downloadUrl) { }
});
}
});
in the upload image function
ref.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
callback.journey(uri);
Log.d(TAG, "onSuccess: uri= "+ uri.toString());
}
});
}
});
and in saveObjectInDB function you do this
db.collection(DATABASE).add(O)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.w(TAG, "Document upload complete");
callback.result(Result.SUCCESS);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding uploading document", e);
callback.result(Result.FAILED);
}
});
I have two functions working fine in an android app with Firebase. I can upload an image to my storage and I can add attributes to my database, but how do I build a relationship between the two entries.
Here's my database code:
private void addCar(){
String make = editTextMake.getText().toString().trim();
String model = editTextModel.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
Car car = new Car(make, model, description);
FirebaseUser user = auth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(car);
Toast.makeText(this, "Information Saved....", Toast.LENGTH_LONG).show();
}
And here is my storage code:
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(uploadActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(uploadActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
I'd like a User to be able to pick an image of a car, enter the attributes relating to that image like Make/Model and press an upload button to enter both into Firebase, while knowing that the specific image is related to the specific attributes.
StorageReference filess= storageReference.child("images/" + UUID.randomUUID());
filess.putFile(url)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.e("url", taskSnapshot.getDownloadUrl() + ":");
// Get Url from here and add to your Database
addFirebase(taskSnapshot.getDownloadUrl());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
Firebase insert data
private void addFirebase(String url){
String make = editTextMake.getText().toString().trim();
String model = editTextModel.getText().toString().trim();
String description = getText().toString().trim();
Car car = new Car(make, model, description,url);
FirebaseUser user = auth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(car);
Toast.makeText(this, "Information Saved....", Toast.LENGTH_LONG).show();
}