When I am trying to save file to the firebase storage it always save it with the name 'null'.this is my code:
try {
localFile = createTempImageFile(getExternalCacheDir());
final File finalLocalFile = localFile;
mStorageRef.child("images/" + mRereference).getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.with(getBaseContext())
.load(Uri.fromFile(finalLocalFile))
.into(mIVpicture1);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Load","" + e);
}
});
} catch (IOException e) {
e.printStackTrace();
}
This is the metod createTempImageFile which doesn't work :
public static File createTempImageFile(File storageDir) throws
IOException
{
String timeStamp = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss",
Locale.getDefault()).format(new Date());
String imageFileName = "photo_" + timeStamp;
return File.createTempFile(
imageFileName,
".jpg",
storageDir
);
}
This is a code for upploading a pictute to the firebase storage
public void uploadFileInFireBaseStorage (Uri uri){
UploadTask uploadTask = mStorageRef.child("images/" + mRereference).putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred());
Log.i("Load","Upload is " + progress + "% done");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
final String download_url = String.valueOf(downloadUrl);
Log.i("Load" , "Uri donwnload" + download_url);
}
});
}
Related
I want to make app upload many images to firestore storage and get all of the urls of those images and post it in firestore database by using java in android.
I have this function to post on database
public void uploadFile(Map<String,Object> item , String phone){
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Users").document().collection(phone).add(item)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(getApplicationContext(),"Upload Complete",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
The data is a hashmap of data I will post to the database. This data contains this information:
Map<String,Object> data = new HashMap<>();
data.put("name" , name);
data.put("phone" , phone);
data.put("city" , city);
data.put("itemName" , itemName);
data.put("price" , price);
data.put("type" , type);
data.put("subtype" , subtype);
data.put("cond" , cond);
data.put("details" , details);
and I have this function to upload photo
public void upLoadImage(File data,Map<String,Object> list,int KEY){
Uri file = Uri.fromFile(data);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference().child("images/"+file.getLastPathSegment());
UploadTask uploadTask = storageRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
url = "fails " + e.getMessage();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
if(KEY == 1){
list.put("image1",String.valueOf(uri));
}else if(KEY ==2){
list.put("image2",String.valueOf(uri));
}else if(KEY == 3){
list.put("image3",String.valueOf(uri));
}
}
});
}
});
this function take two argument data:
list that will push download url inside it
image file
I want to run it just like this
uploadImage(path1,data,1);
uploadImage(path2,data,2);
uploadImage(path3,data,3);
uploadfile()
This means that I want to upload image and complete then upload sec image and complete etc., then run uploadfile because my problem that uploadfile not wait upload image to complete.
The problem was resolved by write upload image like this
public void upLoadImage(String path,String path2, String path3,Map<String,Object> list,int KEY,String Auth){
if(!path.equals("empty") && path != null){
Toast.makeText(getApplicationContext(),"path = " + path,Toast.LENGTH_LONG).show();
Uri file = Uri.fromFile(new File(path));
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference().child("images/"+file.getLastPathSegment());
UploadTask uploadTask = storageRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"No Connection",Toast.LENGTH_LONG).show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
if(KEY == 1 ){
list.put("image1",String.valueOf(uri));
upLoadImage(path2,"null",path3,list,2,Auth);
}
if(KEY == 2){
list.put("image2",String.valueOf(uri));
upLoadImage(path3,"null","null",list,3,Auth);
}
if(KEY == 3){
list.put("image3",String.valueOf(uri));
uploadFile(list,Auth);
}
}
});
}
});
}else {
uploadFile(list,Auth);
}
}
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
// ...
}
}
});
I have created an activity where the user can select pdf and audio file from the storage and upload to the firebase storage if the file size is less than 16mb. to check the file size I have created a method where filesize is been compared whether the file size is less than 16mb. this activity should upload the file but whenever I select any file an error occurs says
error: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=438, result=-1, data=Intent {
dat=content://com.android.providers.downloads.documents/document/35
flg=0x1 }} to activity
{com.nanb.Alpha/com.nanb.Alpha.personalchat.personalChat}:
java.lang.NullPointerException.
I have searched for the solution and found that the file isn't selected but didn't get any solution tor to remove the error.
the code is given below that I have used:
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checker = "audio";
Intent audioIntent = new Intent();
audioIntent.setAction(Intent.ACTION_GET_CONTENT);
audioIntent.setType("audio/*");
startActivityForResult(Intent.createChooser(audioIntent,"Select Audio"),438);
}
});
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checker = "pdf";
Intent pdfIntent = new Intent();
pdfIntent.setAction(Intent.ACTION_GET_CONTENT);
pdfIntent.setType("application/pdf");
startActivityForResult(Intent.createChooser(pdfIntent,"Select pdf file"),438);
}
});
I have also tried to put
Intent audioIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(audioIntent, "Select Audio"), AUDIO_REQUEST);
still get the same error. Rest all the codes are as follows:
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 438 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
imagefile = data.getData();
String filePath = this.getRealPathFromURI(imagefile);
Long Filelength = this.getfilesize(filePath);
if(checckfilesize(Filelength).equals("ok")) {
if (checker.equals("pdf")) {
pdfFilemessage(filePath);
}else{
String fileName = this.getfilename(filePath);
audiofilemessage(filePath,fileName);
}
}
}
public Long getfilesize(String filepath){
File filedata = new File(filepath);
Long fileLength = filedata.length();
fileLength = fileLength/1024;
return fileLength;
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {
MediaStore.Audio.Media.DATA
};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// Toast.makeText(personalChat.this,
Long.toString(cursor.getLong(sizeIndex)),Toast.LENGTH_SHORT).show();
return cursor.getString(column_index);
}
public String checckfilesize(Long Filelength){
String checkstate;
if(Filelength < 16000 ){
checkstate = "ok";
}else{
checkstate = "file large than 16mb.";
}
return checkstate;
}
private String getfilename(String filepath){
File file = new File(filepath);
String filename = file.getName();
return filename;
}
retrieve temp file
private void reciverpdftempImage(Uri imagefile, String msgpushId) {
int pageNumber = 0;
PdfiumCore pdfiumCore = new PdfiumCore(this);
try {
ParcelFileDescriptor fd = getContentResolver().openFileDescriptor(imagefile, "r");
PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
pdfiumCore.openPage(pdfDocument, pageNumber);
int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber);
int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber);
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
pdfiumCore.renderPageBitmap(pdfDocument, bmp, pageNumber, 0, 0, width, height);
saveImage(bmp,msgpushId);
pdfiumCore.closeDocument(pdfDocument); // important!
} catch(Exception e) {
//todo with exception
}
}
upload the audio and pdf file to the firebase
private void audiofilemessage(String vfilePath,final String filename) {
StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Audio");
final String msgSenderref = "Chats/" + mAuth.getCurrentUser().getUid() + "/" + userid;
final String msgReciverref = "Chats/" + userid + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference usermsgKeyRef = rootref.child("Chats").child(mAuth.getCurrentUser().getUid()).child(userid).push();
final String msgPushId = usermsgKeyRef.getKey();
final StorageReference filePath = imagereference.child(msgPushId+"."+"mp3");
uploadTask = filePath.putFile(Uri.fromFile(new File(vfilePath)));
String destinationfile = Environment.getExternalStorageDirectory()+"/Alpha/Audio/Send/"+msgPushId+".mp3";
copyFileOrDirectory(vfilePath,destinationfile);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String myUrl = downloadUri.toString();
Toast.makeText(getApplicationContext(),myUrl,Toast.LENGTH_SHORT).show();
// uploadfiletotheserver(myUrl,filename,checker,msgPushId,msgSenderref,msgReciverref);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(personalChat.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void pdfFilemessage(String vfilePath) {
StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Doc");
final String msgSenderref = "Chats/" + mAuth.getCurrentUser().getUid() + "/" + userid;
final String msgReciverref = "Chats/" + userid + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference usermsgKeyRef = rootref.child("Chats").child(mAuth.getCurrentUser().getUid()).child(userid).push();
final String msgPushId = usermsgKeyRef.getKey();
reciverpdftempImage(imagefile,msgPushId);
final StorageReference filePath = imagereference.child(msgPushId+"."+"pdf");
uploadTask = filePath.putFile(imagefile);
String destinationfile = Environment.getExternalStorageDirectory()+"/Alpha/pdf/Send/"+msgPushId+".pdf";
copyFileOrDirectory(vfilePath,destinationfile);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String myUrl = downloadUri.toString();
Toast.makeText(getApplicationContext(),myUrl,Toast.LENGTH_SHORT).show();
//uploadpdfTempfile(myUrl,imagefile,checker,msgPushId,msgSenderref,msgReciverref);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(personalChat.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void uploadpdfTempfile(final String myUrl,final Uri imagefile,final String checker, final String msgPushId, final String msgSenderref, final String msgReciverref) {
StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Doc").child("temp");
Uri file = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/Alpha/PDF/temp/"+msgPushId+".png"));
final StorageReference fileuploadpath = imagereference.child(msgPushId+".png");
uploadTask = fileuploadpath.putFile(file);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return fileuploadpath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUri = task.getResult();
String myfileUrl = downloadUri.toString();
//Toast.makeText(personalChat.this,myfileUrl,Toast.LENGTH_SHORT).show();
uploadpdfdatatotheserver(myUrl,imagefile,checker,msgPushId,msgSenderref,msgReciverref,myfileUrl);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(personalChat.this,"Error:"+ e,Toast.LENGTH_SHORT).show();
}
});
}
private void uploadpdfdatatotheserver(String myUrl, Uri imagefile, String checker, final String msgPushId, final String msgSenderref, final String msgReciverref,final String myfileurl) {
Map msgpicbody = new HashMap();
msgpicbody.put("message",myUrl);
msgpicbody.put("name",imagefile.getLastPathSegment());
msgpicbody.put("type",checker);
msgpicbody.put("ffrom",mAuth.getCurrentUser().getUid());
msgpicbody.put("to",userid);
msgpicbody.put("date", savecurrentDate);
msgpicbody.put("time",savecurrentTime);
msgpicbody.put("messageId",msgPushId);
msgpicbody.put("tempfile",myfileurl);
Map msgBodyDetail = new HashMap();
msgBodyDetail.put(msgSenderref + "/" +msgPushId,msgpicbody);
msgBodyDetail.put(msgReciverref + "/" +msgPushId,msgpicbody);
rootref.updateChildren(msgBodyDetail).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
loadingBar.dismiss();
msginput.setText(null);
frameLayout.setVisibility(View.GONE);
}else{
loadingBar.dismiss();
msginput.setText(null);
frameLayout.setVisibility(View.GONE);
Toast.makeText(personalChat.this,"error",Toast.LENGTH_SHORT).show();
}
}
});
}
logcat
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=438, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/35 flg=0x1 }} to activity {com.nanb.Alpha/com.nanb.Alpha.personalchat.personalChat}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:4090)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4133)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1534)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6125)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
Caused by: java.lang.NullPointerException
at java.io.File.<init>(File.java:262)
at com.nanb.Alpha.personalchat.personalChat.getfilesize(personalChat.java:813)
at com.nanb.Alpha.personalchat.personalChat.onActivityResult(personalChat.java:179)
at android.app.Activity.dispatchActivityResult(Activity.java:7194)
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 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();
}