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) {
}
});
}
Related
have a problem, I'm working on a university project, I have two tables in firebase, the gallery table that contains the photos of the itinerary and the itinerary table that contains the various itineraries of the users now I have to make sure that the id of the itinerary and the ID of the image so as to have a photo corresponding to each itinerary ì, also created by the same user. I did so:
public void addImageItinerary() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
if (images != null) {
StorageReference itineraryRef = storageReference.child("itinerary_image/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpg");
itineraryRef.putFile(images).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
itineraryRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String itineraryId = referenceDb.child("Itinerary").push().getKey();
Log.i("itineraryId", itineraryId);
HashMap<String, Object> map = new HashMap<>();
map.put("image", uri.toString());
referenceDb.child("Gallery").child(FirebaseAuth.getInstance().getCurrentUser().getUid()+ "/" + itineraryId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// APRO SCHERMATA MAPPA
// openMapFragment();
Toast.makeText(insertImage_fragment.getActivity(), "ok", Toast.LENGTH_SHORT).show();
} else {
//ERRORE
Toast.makeText(insertImage_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertImage_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else{
Toast.makeText(insertImage_fragment.getActivity(),"Please add image", Toast.LENGTH_SHORT).show();
}
}
enter image description here
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.
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();
}
});
I created a profile for a user and i've got one problem:
The loading is slow - due to every pic is 4mb and it takes about 20 sec to load,
I need some help about image compression/methods to reduce data and make the program download the img and put it into the profile faster.
Im using android studio and java
this is my code:
Here im adding to the user some information
private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myref = firebaseDatabase.getReference(firebaseAuth.getUid());
userProfile user = new userProfile(Sphone, Semail, name);// simple object get and set
myref.setValue(user);
UpdateUserInfo(name, pickedImgUri, firebaseAuth.getCurrentUser());
}
Here its uploading the image
private void UpdateUserInfo(final String name, Uri pickedimguri, final FirebaseUser currnetUser) {
StorageReference mStorageReference = FirebaseStorage.getInstance().getReference().child("users_photos");
final StorageReference imagefilepath = mStorageReference.child(pickedimguri.getLastPathSegment());
imagefilepath.putFile(pickedimguri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
imagefilepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currnetUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
showMessage("Register complete");
}
}
});
}
});
}
});
}
And this is the loading code to the user profile after creating it and entering the main screen:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
name = getView().findViewById(R.id.textView);
profilepic = getView().findViewById(R.id.profilepic);
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference uidRef = rootRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String nameE = dataSnapshot.child("name").getValue(String.class);
String phone = dataSnapshot.child("phone").getValue(String.class);
Log.d("TAG", nameE + ", " + email + ", " + phone);
name.setText("Welcome " + nameE);
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString()).into(profilepic);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
}
Thanks!
Here's an example of compressing an image for firebase storage. This is the method I'm using, and it reduces images between 2-4mb down to <300kb. JPEG is a lossy format and I use a level of 75 for compression, which still retains most of the detail in an image.
//Start with URI of image
if (uri != null) {
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] bytes = baos.toByteArray();
StorageReference reference = FirebaseStorage.getInstance().getReference("whatever folder you place the images in/" + name_of_image + ".jpg");
UploadTask uploadTask = reference.putBytes(bytes);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
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) {