Pushing Firebase storage download URLs to Firebase cloud Firestore - android

How can I push the download URL of Firebase storage files to the Firestore cloud? I have a project that can upload PDF files to Firestore storage, but I can't push the download URL of the uploaded files to the Firestore cloud.
I need to catch the upload URL for every single file and send it to the document in the firestore to be able to download it. I'm uploading and downloading PDF files.
Here is my code:
public class pdfUploader extends AppCompatActivity {
private StorageReference mStorageRef;
Button upload;
Button select;
int CODE=215;
private CollectionReference dbFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_uploader);
mStorageRef = FirebaseStorage.getInstance().getReference();
upload = findViewById(R.id.upload);
select = findViewById(R.id.choose);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectFile();
}
});
}
public void selectFile () {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i,"Select a file"), CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String filePath = data.getDataString();
Uri SelectedFileLocation=Uri.parse(filePath);
UploadFile(SelectedFileLocation);
super.onActivityResult(requestCode, resultCode, data);
}
public void UploadFile( Uri file) {
Toast.makeText(this, "Please wait.. the file is uploading!", Toast.LENGTH_SHORT).show();
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = mStorageRef.child(Objects.requireNonNull(file.getLastPathSegment()));
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(pdfUploader.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
}

Assign this Variable on Top
FirebaseFirestore db;
//In oncreateView we have to assign now db so.
db = FirebaseFirestore.getInstance();
Code for get File uri :
riversRef.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
//After upload Complete we have to store the Data to firestore.
Map<String, Object> file = new HashMap<>();
file.put("url", downloadUrl.toString()); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document name Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
}
});
If download url expires there's better way to store you're image file in you're storage and firestore
Code :
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = //Put path of storage it will be something like [images/filename.jpg(Put your extension of file)] this path from firebase storage
Map<String, Object> file = new HashMap<>();
file.put("url", path); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document id Here*/")
.set(file)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
the above code will be useful and better when you're dealing with images and read this docs for further details

Related

How do I set download URL for an image to firestore database and realtime Database

I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice

how to get an image path in firebaseStorage to firebaseDatabase

hi every one am making an app that use firebaseDatabase for Users info and firebaseStorage to save the image and i want to put the path of the image uploaded to firebaseStorage in firebaseDatabase under User info so i can display the image like profile pic so am using this to upload image and mainActivity to show the image . i do search for solution and got some but it didnt work or i didnt know how to make it work . am new at android
upload image
public String getExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getMimeTypeFromExtension(contentResolver.getType(uri));
}
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
// Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
MainActvity
public class MainActivity extends AppCompatActivity {
ImageView profilePic ;
TextView nameProfile ;
DatabaseReference databaseReference ;
FirebaseUser fUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
profilePic=findViewById(R.id.imageProfile);
nameProfile = findViewById(R.id.nameProfile);
fUser=FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(fUser.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
nameProfile.setText(user.getName());
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profilePic);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
that work for me
final StorageReference reference = mStorageReference.child(System.currentTimeMillis() + "." + getExtension(imageUri));
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(
new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
}
}
);
}
});
public void uploadfile(){
if(uri!=null){
final StorageReference filereference=storageReference.child(System.currentTimeMillis()+"."+getFileExtension(uri));
filereference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
filereference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload=new Upload(editText1.getText().toString(),uri.toString());
String str=databaseReference.push().getKey();
databaseReference.child(str).setValue(upload);
progressBar.setVisibility(View.INVISIBLE);
progressBar2.setVisibility(View.VISIBLE);
final Timer timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
counter++;
progressBar2.setProgress(counter);
if (counter==100){
toast.show();
progressBar2.setVisibility(View.INVISIBLE);
counter=0;
timer.cancel();
}
}
};timer.schedule(timerTask,1,15);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
Hello my friend please copy-paste your function like this
private void uploadImage() {
StorageReference reference = mStorage.child(System.currentTimeMillis()+"."+getExtension(imageUri));
uploadTask= reference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uploadedImageUrl = uri.toString();
// Now you have your image in (uploadedImageUrl) variable so write your code to upload in firebaseDatabase and enjoy
}
});
Toast.makeText(AddImageActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(AddImageActivity.this,MainActivity.class);
startActivity(ii);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}

How to get URL from Firebase Storage and send it to database? [duplicate]

This question already has an answer here:
getDownloadURL isn't inputting the link i need
(1 answer)
Closed 2 years ago.
I'm trying to upload an image to Firebase Storage and after that send the URL of this image to Firebase Database. The Uri is correct, but when I try to set it on my object, the method singleDetection.setImage(imagePath) is setting nothing. Here is my code:
Bitmap image = detectedFaceItems.get(0).getImage();
StorageReference storageRef = storage.getReference();
StorageReference imagesRef = storageRef.child("2.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageTask<UploadTask.TaskSnapshot> uploadTask = imagesRef.putBytes(data)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to sent a file", Toast.LENGTH_LONG).show();
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
You are uploading the image right, but your call to Firebase after successfully uploading the image using storageRef.child("2.jpg").getDownloadUrl(). not that right as you already don't know the generated Uri which you can get from the snapshot that is returned back with the taskSnapshot.
So replace the below part of code:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
With:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get upload url
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String imagePath = String.valueOf(task.getResult());
singleDetection.setImage(imagePath);
}
});
}
});
Note: here you've uploaded the image itself, but don't upload its Uri, so you can to decide to upload it to firebase as you'd like.

Firebase Storage - Link not created

I am trying to upload an image and a document to the firebase storage and upload the links created from both to the Real-Time DB, everything happening on a button's click.
But in the firebase DB, the links are not uploaded while the other text I upload along with them is there.
Storage upload code:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
});
}
Where updata is the button, UploadData is the class for holding those all those values...
After I click the button the image is stored in the Storage while the Database holds nothing but,
data {
name:"given name"
info:"given info"
}
while it has to have included the ImgLink and DocLink.
Where does it lose track?
Try this code
Declare this object globally
Uri uri;
Set uri when user fetches the Image from the gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
jimg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here sUrl will have downloadURL
private void uploadImage() {
try {
final StorageReference ref = storageReference.child( UUID.randomUUID().toString() );
//uploads the image
ref.putFile( uri ).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener( new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Uri downloadUrl = uri;
sUrl = downloadUrl.toString();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
} );
}
} );
}catch (Exception e){}
}
Each onSuccess method is called asynchronously, after the call to the server has completed. Since this takes time, you main code continues, and this means you're writing to the database, before the download URL is available.
It's easiest to see this if you place some log statements in your code:
Log.i("STORAGE", "Starting to upload image data");
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i("STORAGE", "Image data uploaded, getting download URL");
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i("STORAGE", "Got download URL");
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
...
uploadData.setName(event);
uploadData.setInfo(info);
Log.i("STORAGE", "Writing info to database");
databaseReference.child(event).setValue(uploadData);
The output of this is:
Starting to upload image data
Writing info to database
Image data uploaded, getting download URL
Got download URL
This is probably not what you expected, but it is working as intended, and completely explains why the download URL isn't written to the database: by the time you write to the database, the download URL hasn't been loaded yet.
The solution to this problem is always the same: any code that requires the download URL, need to be inside the onSuccess method that gets called when the download URL is retrieved (or at least needs to be called from there).
So something like:
updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before uploading both the doc and img..
progressDialog.setTitle("Uploading Images");
progressDialog.show();
final UploadData uploadData=new UploadData();
if(ImgPathUri!=null){
StorageReference str=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(ImgPathUri));
str.putFile(ImgPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String ImgLink=uri.toString();
linkimg=ImgLink;
uploadData.setImgURL(linkimg);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(addEventActivity.this, "fucked ra", Toast.LENGTH_SHORT).show();
finished=false;
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
if(DocPathUri!=null){
StorageReference storageReference1=storageReference.child(StoragePath + System.currentTimeMillis() + "." + getExtension(DocPathUri));
storageReference1.putFile(DocPathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String DocLink=uri.toString();
linkdoc=DocLink;
uploadData.setDocURL(linkdoc);
progressDialog.dismiss();
String info=infoText.getText().toString();
String event=eventName.getText().toString();
uploadData.setName(event);
uploadData.setInfo(info);
//uploading the event name,info and other file links to the RTDB under the event name
databaseReference.child(event).setValue(uploadData);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("TAG_FOR_FAILURE LOG", "On Failure: The exception", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finished=false;
Toast.makeText(addEventActivity.this, "doc fucked", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}

How to get Firebase Storage image URL in android studio?

I want to display image on imageView from Firebase Storage without saving the picture in the device, so I've tried to use the highlighted URL (from the photo below) and it works but I don't want to write the address manually.
How can I get the address using the code?
p.s I tried dataBaseStorageRef.getDownloadUrl() and it gives me another URL, not the one from the picture.
enter image description here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final StorageReference filePath = storage.child("books").child(""+AddBook.book_id+1).child("photo.jpg");
if(requestCode == RESULT_GALLERY){
if (resultCode == RESULT_OK){
pic_uri = data.getData();
book_img.setImageURI(pic_uri);
filePath.putFile(pic_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(AddBookActivity.this, "Upload done", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddBookActivity.this, "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
img_addr = filePath.getDownloadUrl().toString();
Toast.makeText(this, "picture was selected", Toast.LENGTH_SHORT).show();
}
}
}
Then, I'm trying to display the pic from img_addr from another activity
and it doesn't work because the address of image_addr is not good (if I replace manually img_addr to the address from the attached link it works)
if(books_list.get(i).img_addr!=null){
Toast.makeText(v.getContext(),books_list.get(i).img_addr,Toast.LENGTH_LONG).show();
Picasso.with(v.getContext()).load(books_list.get(i).img_addr).resize(50,50).into(img);
}
Thanks to those who help
You can use continueWithTask method to return the download url
Like the following:
final UploadTask uploadTask = filepath.putFile(uri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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 filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Make getDownloadUrl() asynchronous by adding onsuccess and onfailure listeners to it.
Your complete image upload task should look like below
photoReference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoReference.getDownloadUrl().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//do something
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//get your image uri here
Uri imgUrl = uri;
String imgStringUrl = imgUrl.toString();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// do something
}
});
You can get download URL from below method:
private void uploadToStorage(String imgPath, String fileName) {
Uri file = Uri.fromFile(new File(imgPath));
StorageReference storageReference = mStorageRef.child(userId + "/images/" + fileName);
storageReference.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
downloadUrl.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.v(TAG, "Media is uploaded");
String downloadURL = "https://" + task.getResult().getEncodedAuthority()
+ task.getResult().getEncodedPath()
+ "?alt=media&token="
+ task.getResult().getQueryParameters("token").get(0);
Log.v(TAG, "downloadURL: " + downloadURL);
//save your downloadURL
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.v(TAG, "Media is not uploaded");
Log.v(TAG, "Exception: " + exception.getLocalizedMessage());
}
});
}
You can also get scheme name & query from methods under task.getResult()

Categories

Resources