implementing addOnProgressListener In Firebase - java

In my code i want to add OnProgressListener, but can't work. It gives me a syntax error.
Cannot resolve method 'addOnProgressListener' in 'Task'
How i can do this?
Please rewrite the code for me.
I Want to show progress dialog percentage.
For example: "uploading video 98%"
private void uploadImage_10() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Posting....");
pd.show();
if (video_url != null) {
final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(video_url));
uploadTask = fileReference.putFile(video_url);
String desc = description.getText().toString();
if (desc.length() < 20) {
description.setError("Please Insert Document to long");
if (TextUtils.isEmpty(desc)) {
description.setError("Please insert Description");
Toast.makeText(this, "Please Insert Description", Toast.LENGTH_SHORT).show();
}
pd.dismiss();
} else {
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();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
miUrlOk = downloadUri.toString();
DatabaseReference reference = FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Posts_video");
String postid = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("postid", postid);
hashMap.put("time_post", ServerValue.TIMESTAMP);
hashMap.put("postvideo", miUrlOk);
hashMap.put("description", description.getText().toString());
hashMap.put("category", category.getSelectedItem().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postid).setValue(hashMap);
pd.dismiss();
startActivity(new Intent(PostActivityvideo.this, MainActivity.class));
finish();
} else {
Toast.makeText(PostActivityvideo.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PostActivityvideo.this, 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((int) progress + "");
}
});
}
} else {
Toast.makeText(PostActivityvideo.this, "No image selected", Toast.LENGTH_SHORT).show();
}
}

From what I can see you may have defined uploadTask as a Task.
To be able to call addOnProgressListener ,you'll want to declare it as an UploadTask.

Related

Upload multiple image to firebase and retrieve into viewpage

I want to upload multiple image to firebase and retrieve into view page . I am only able to upload the multiple image but getting only one Uri getdlownload link in Realtime database due to which only one image is fetching into view page
enter code here
private void sendDataToFirebase() {
progressBar.setVisibility(View.VISIBLE);
id = databaseReference.push().getKey();
Toast.makeText(this, "Sending", Toast.LENGTH_SHORT).show();
photoUri=new Uri[photoUris.size()];
for (i = 0; i < photoUris.size(); i++) {
photoUri[i] = photoUris.get(i);
// File fileUriPhoto = new File(SiliCompressor.with(this).
//
// compress(FileUtils.getPath(this, photoUri), new File(this.getCacheDir(), "AddPostPhotos")));
// Uri uri = Uri.fromFile(fileUriPhoto);
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = mfirebaseStorage.child("AddPost/" + photoUri[i].getLastPathSegment());
imageFolder.putFile(photoUri[i]).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
progressBar.setVisibility(View.GONE);
addPostModel = new AddPostModel();
addPostModel.setCategories(spinner.getSelectedItem().toString().trim());
addPostModel.setSubcategories(spinner1.getSelectedItem().toString().trim());
addPostModel.setTitle(name.getText().toString().trim());
addPostModel.setAuthor(author.getText().toString().trim());
addPostModel.setPrice(price.getText().toString().trim());
addPostModel.setDesc(desc.getText().toString().trim());
addPostModel.setUserUid(mCurrentUser.getUid());
addPostModel.setPhoneNumaber(mCurrentUser.getPhoneNumber());
addPostModel.setDateTime(date);
addPostModel.setImageUrl(photoUri[i].toString());//Here is the problem//
addPostModel.setKey(id);
databaseReference.child(id).setValue(addPostModel);
}
});
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(AddPostFormActivity.this, "Post added", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddPostFormActivity.this,Dashboard.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddPostFormActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
try this method...
imageFolder.putFile(photoUri[i]).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Here you are get the download url
Task<Uri> urlTask =taskSnapshot.getStorage().getDownloadUrl();
Uri downloadUrl = urlTask.getResult();
final String sdownload_url = String.valueOf(downloadUrl);
progressBar.setVisibility(View.GONE);
addPostModel = new AddPostModel();
addPostModel.setCategories(spinner.getSelectedItem().toString().trim());
addPostModel.setSubcategories(spinner1.getSelectedItem().toString().trim());
addPostModel.setTitle(name.getText().toString().trim());
addPostModel.setAuthor(author.getText().toString().trim());
addPostModel.setPrice(price.getText().toString().trim());
addPostModel.setDesc(desc.getText().toString().trim());
addPostModel.setUserUid(mCurrentUser.getUid());
addPostModel.setPhoneNumaber(mCurrentUser.getPhoneNumber());
addPostModel.setDateTime(date);
addPostModel.setImageUrl(photoUri[i].toString());//Here is the problem//
addPostModel.setKey(id);
databaseReference.child(id).setValue(addPostModel);
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(AddPostFormActivity.this, "Post added", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddPostFormActivity.this,Dashboard.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddPostFormActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Object does not exists at location at android firebase upload file

I am trying to create an app using firebase storage service. I have a function that saves an image from device local storage, uses the URI of the picture to save it to firebase. When trying to upload the image to firebase server I get "object does not exist at location", probaby meaning there is a problem which my URI.
I am adding the entire activity so you can see what is going on -
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int PICK_IMAGE_REQUEST = 1;
public static final int DELAY_MILLIS = 5000;
private Button buttonChooseImage, buttonUpload;
private TextView textViewShowUpload;
private EditText editTextFileName;
private ImageView imageView;
private ProgressBar progressBar;
private Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChooseImage = findViewById(R.id.button_choose_image);
buttonUpload = findViewById(R.id.button_upload);
textViewShowUpload = findViewById(R.id.text_view_show_uploads);
editTextFileName = findViewById(R.id.edit_text_file_name);
imageView = findViewById(R.id.image_view);
progressBar = findViewById(R.id.progress_bar);
buttonChooseImage.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
textViewShowUpload.setOnClickListener(this);
storageReference = FirebaseStorage.getInstance().getReference("uploads");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_choose_image:
openFileChooser();
break;
case R.id.button_upload:
uploadFile();
break;
case R.id.text_view_show_uploads:
break;
}
}
private String getFileExtension(Uri uri) {
ContentResolver cr = getContentResolver();
MimeTypeMap mine = MimeTypeMap.getSingleton();
return mine.getExtensionFromMimeType(cr.getType(uri));
}
private void uploadFile() {
if (imageUri != null) {
StorageReference fileRefrence = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
fileRefrence.putFile(imageUri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, DELAY_MILLIS);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(editTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, 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());
progressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}
}
Am I implementing URI incorrectly?
edit -
tryed this solution from comments, yet still getting the same error -
private void uploadFile() {
if (imageUri != null) {
StorageReference fileReference = storageReference.child("images/" + imageUri.getLastPathSegment());
UploadTask uploadTask = fileReference.putFile(imageUri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, DELAY_MILLIS);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(editTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, 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());
progressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
For me Uploading was possible with this code. I got this at https://www.youtube.com/watch?v=lPfQN-Sfnjw&list=PLrnPJCHvNZuBf5KH4XXOthtgo6E4Epjl8&index=4 in the comment section. Also set the authentication in your firebase storage to true
private void uploadFile(){
if(mImageUri!=null){
storageReference.putFile(mImageUri).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();
}
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
Uri downloadUri = task.getResult();
Log.e("TAG", "then: " + downloadUri.toString());
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
downloadUri.toString());
databaseReference.push().setValue(upload);
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(this, "Please upload image!", Toast.LENGTH_SHORT).show();
}
}
This is the code what i have used for my project and its working...
Also make sure that
you have make rules public on firebase storage
added the permission in your manifest file for access phone storage and internet
added all required dependencies for firebase storage access
StorageReference storageReference;
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference refStorage = storageReference.child("images/"+uri.getLastPathSegment());
UploadTask uploadTask = refStorage.putFile(uri);
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 new Exception("task is not succeeded");
} return refStorage.getDownloadUrl();
}//end of throws Exception method
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downUri = task.getResult();
} else {
// Handle failures
// ...
Log.d("<<<<<<<<", "<<<<<<<<<<<<<<<<<<<< not uplooaded ");
}
}//end of onComplete()for getting download uri
});
Replace the following code:
StorageReference fileRefrence = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
with this:
StorageReference fileRefrence = storageReference.child(imageUri.getLastPathSegment());
Try this code
StorageReference imageReference = storageReference.child("uploads");
UploadTask uploadTask = imageReference.putFile(imageuri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(verify.this, "Upload failed!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {

I want to retrieve videos from firebase storage

I am working on simple firebase app in which I upload user info as registration data and uploading videos in storage. Path of videos is also stored in realtime database as nested child of every particular user which is working properly, but I don't know how to retrieve video and set in user profile with other user information. I need code to retrieve video from storage.
case PICK_VIDEO_REQUEST:
if (resultCode == RESULT_OK) {
selectedVideoUri = data.getData();
userUid = FirebaseAuth.getInstance().getCurrentUser().getEmail();
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
filename = data.getData().getLastPathSegment();
tv_file_path.setText(filename);
videoRef = storageRef.child("/videos/" + userUid + "/" + filename);
//TODO: save the video in the db
}
break;
`//Button upload data in firebase
btn_upload_notes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData(selectedVideoUri);
try {
if (FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(value.getT_email())) {
file_name = filename;
notes_Category = text;
lecture_topic = et_topic.getText().toString().trim();
id = mDatabase.push().getKey();
NotesModelClass notesModelClass = new NotesModelClass(id, notes_Category, lecture_topic, file_name);
mDatabase.child(value.getT_id()).child("Video Notes").child(id).setValue(notesModelClass);
return;
}
}
catch (Exception ex){
throw ex;
}
}
});
`
private void uploadData(Uri videoUri) {
if (videoUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
UploadTask uploadTask = videoRef.putFile(videoUri);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Upload Complete", 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 + "%");
}
});
} else {
Toast.makeText(MainActivity.this, "Nothing to upload", Toast.LENGTH_SHORT).show();
}
}
Try this code
Retrive single video.
StorageReference videoRef = storageRef.child("/videos/" + userUid + "/" + filename);
final long ONE_MEGABYTE = 1024 * 1024;
videoRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Transform bytes to a video, play
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Retrieve multiple video
StorageTask<UploadTask.TakeSnapshot> storageTask;
storageTask = yourStorageRefernce.putFile(videoUri);
storageTask.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();
}
return yourStorageRefernce.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
arrayList.add(downloadUri.toString());
}
}
});
Help me random video in firebase
private void loadVideosFromFirebase() {
videoArrayList=new ArrayList<>();
DatabaseReference reb = FirebaseDatabase.getInstance().getReference().child("Videos");
reb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds:dataSnapshot.getChildren()) {
ModelVideo modelVideo = ds.getValue(ModelVideo.class);
videoArrayList.add(modelVideo);
}
adapterVideo = new AdapterVideo(VideosActivity.this,videoArrayList);
videosRv.setAdapter(adapterVideo);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}

How to Fix This (.getDownloadUrl()) Not Coming In New Version Of Firebase DataBase

how to fix .getDownloadUrl() In New Versions Based On My Code
Am Unable To Find .getDownloadUrl() In New Versions Can You Please tell Me The Answer
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
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() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, 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());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
Please Sir Fix This Problems
Tl;Dr
Instead of takeSnapshot.getDownloadUrl() write, takeSnapshot.getMetadata().getReference().getDownloadUrl()
Longer version.
Firebase API has changed a lot, the new UploadTask.TakeSnapshot API doesn't have the method getDownloadUrl() anymore.
You can use the the method getMetaData which returns a StorageMetaData object. The StorageMetaData object has a method getReference which returns StorageReference, which has the method getDownloadUrl which will return you a Task<uri> object.
you can also look at this piece of code from FireBase docs, where it calls getDownloadUrl on StorageReference class.

How to retrieve the download URL of an image from Firebase Storage?

I am watching an old tutorial about Firebase Storage. The getDownloadUrl() method from UploadTask.TaskSnapshot is no longer existent, and the documentation fails to be clear to me.
What I've implemented so far is the upload process and I can confirm it works, but getting the URL is a pain and I can't make the way they explain how to do it because:
1) Creating a Task<Uri> urlTask = uploadTask.add[...]() will result in the following error on the IDE:
I don't understand because it is specified in the docs.
2) Using reference.getDownloadUrl() will display a different URL compared to what is shown on the console when seeing the details of the uploaded image. The download URL the console shows is
https://firebasestorage.googleapis.com/v0/b/chatroom-e44e6.appspot.com/o/chat_photos%2F73185640?alt=media&token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
while logging will show
com.google.android.gms.tasks.xxx#xxxxxxx
My full code at the moment:
if (requestCode == RC_PHOTO_PICKER) {
if (data != null) {
Toast.makeText(MainActivity.this, "Uploading...", Toast.LENGTH_SHORT).show();
Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);
upload.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnCompleteListener(this, new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ChatroomMessage message = new ChatroomMessage(null, mUsername, reference.getDownloadUrl().toString()); // <- com.google.android.gms.tasks.xxx#xxxxxxx
mMessagesDatabaseReference.push().setValue(message);
Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
}
});
}
}
My app already has Firebase UI implemented to handle login operations, and the rules are
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
I put the effort and wasted more time but here is the more generic and working solution
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/" +currentFirebaseUser.getUid() + "");
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Log.e("uri12",downloadUrl+"This is uri of image download");
Toast.makeText(AddItemActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddItemActivity.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 + "%");
}
});
}
}
You have Permission denied error it means you don't have permision for access data from firebase. Please check here
if your security rules is defined public then here is no need for permission and if it isn't public or secured then you need to login by auth before you getting data from firebase and if login success then you can continue your work.
check this it will help you to understanding firebase security rules.
After many attempts, I managed to solve it. This is the implementation:
Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);
upload.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
upload.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();
}
return reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUrl = task.getResult();
ChatroomMessage message = new ChatroomMessage(null, mUsername, downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(message);
Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});

Categories