Firebase - Associating Pictures to Users? - android

I am trying to use Firebase to associate uploaded photos to a User so they can be seen on their Profile. Currently it is uploading them to Storage but it doesn't seem to be necessarily associated to a User ID. Shouldn't they show in the "Database" section?
I have looked through https://firebase.google.com/docs/storage/android/upload-files as well as https://firebase.google.com/docs/storage/android/download-files and some stackoverflow articles(Firebase storage structure example) and youtube vids
What I've specifically tried is to get the getCurentUser() to set it to a String and attach that to the image name so I could find it later, but I'm assuming there must be a simpler built-in way?
I login and then go to this RegisterPhotoActivity:
public class RegisterPhotoActivity extends Activity {
Button uploadProfilePhoto;
ImageView checkmarkImage, backArrowImage;
private FirebaseAuth auth;
private static FirebaseUser currentUser;
String currentUserString;
private static final int SELECTED_PICTURE = 1;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registerphoto);
uploadProfilePhoto = (Button) findViewById(R.id.uploadPhotoBTN);
checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);
backArrowImage = (ImageView) findViewById(R.id.leftArrow);
backArrowImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(RegisterPhotoActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
auth = FirebaseAuth.getInstance();
currentUser =
auth.getCurrentUser();
currentUserString = currentUser.toString();
Log.i("CurrentUserString", currentUserString);
storage = FirebaseStorage.getInstance();
//storageReference = storage.getReferenceFromUrl("gs://timeclock-fc.appspot.com").child("20170702_174811.jpeg");
//storageReference = storage.getReferenceFromUrl("gs://timeclock-fc.appspot.com").child(currentUserString);
storageReference = storage.getReferenceFromUrl("gs://timeclock-fc.appspot.com/images").child(currentUserString);
checkmarkImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterPhotoActivity.this, RegisterBusinessActivity.class);
startActivity(intent);
}
});
uploadProfilePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleChooseImage(view);
}
});
}
//END OF onCreate
//Separate methods
//Actually opens the CameraRoll
public void handleChooseImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE); //then goes to onActivityResult
}
public void handleInsertData(View v) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if(requestCode == RESULT_OK) {
Log.i("RegisterActivity", "case 0");
}
break;
case 1:
if(resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
Log.i("RegisterActivity", "selected image = " + selectedImage);
Bitmap imageBitmap = null;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
encodeBitmapAndSaveToFirebase(imageBitmap);
}
break;
}
}
public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //was PNG
byte[] data = baos.toByteArray();
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegisterPhotoActivity.this, "reached onSuccess:", Toast.LENGTH_SHORT).show();
}
});
}
}
Here are my Storage Rules:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
match /images {
// Only an individual user can write to "their" images
match /{userId}/{imageId} {
allow write: if request.auth.uid == userId;
}
}
}
}
My Storage:
My Firebase Node where I'm expecting it to show:

Nothing happens automatically in your database when a photo gets uploaded to Storage. One option would be to add some code to onSuccess in your OnSuccessListener which gets the photo's download url and then writes it to your database under the relevant employee userID. Code might be something like:
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Map<String, Object> map = new HashMap<>();
map.put("photoDownloadUrl", downloadUrl.toString());
userRef.updateChildren(map);

Related

Downloading Photo from Firebase Storage

I have tried really every method i found and it stil didnt worked so I am writing here
I am trying to download photo from Firebase storage from my folder "images" where will be file with same name as current Authorized user ID. Only problem here is that it doesnt work. Only background of object is shown (I am changing photo on ShapableImageView)
Bellow I add code, logs and photo from app .
Code :
private void downloadProfile() {
User localUser = new User("","","0","","",0,0,0);
if(mAuth.getCurrentUser()!=null){
database_ref.child("users").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
localUser.name = snapshot.child("name").getValue().toString();
localUser.mail = mAuth.getCurrentUser().getEmail();
localUser.age = snapshot.child("age").getValue().toString();
localUser.phone = snapshot.child("phone").getValue().toString();
localUser.address = snapshot.child("address").getValue().toString();
localUser.login_method = Integer.parseInt(snapshot.child("login_method").getValue().toString());
localUser.playlist_amount = Integer.parseInt(snapshot.child("playlist_amount").getValue().toString());
localUser.fav_song_amount = Integer.parseInt(snapshot.child("fav_song_amount").getValue().toString());
profile_email.setText(localUser.mail);
profile_name.setText( localUser.name);
age_edit_t.setText(localUser.age);
phone_edit_t.setText(localUser.phone);
address_edit_t.setText(localUser.address);
// Image download
storageReference = storage.getReferenceFromUrl("gs://altas-notas.appspot.com");
storageReference.child("images/"+mAuth.getCurrentUser().getUid()+".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profile_img.setImageURI(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Logs : https://pastebin.com/F0hCxZsv
No matter how i try to download and set photo its transparent or default.
If it matters , I also add part of code that change image :
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
returnUri = data.getData();
Bitmap bitmapImage = null;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
profile_img.setImageBitmap(bitmapImage);
} catch (IOException e) {
e.printStackTrace();
}
//Upload image
storageReference = FirebaseStorage.getInstance().getReference();
storageReference.child("images/"+mAuth.getCurrentUser().getUid()).putFile(returnUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
System.out.println("Upload image is successful!");
}else{
System.out.println("Upload image failed!");
}
}
});
//Upload rest of information
updateProfile();
}
}
}
Here in your code:
storageReference.child("images/"+mAuth.getCurrentUser().getUid()+".jpg")
You don't need the .jpg. Try it like this:
storageReference.child("images/"+mAuth.getCurrentUser().getUid())

Users are not getting stored in Firebase database while images are stored in Firebase storage

I work on a project in Android Studio using Firebase authentication. I am not able to store users in Firebase database while user's images are getting stored in Firebase storage. Because of this, it is not going to the next activity and gets stuck.
ActivitySetupProfileBinding binding;
FirebaseAuth auth;
FirebaseDatabase database;
FirebaseStorage storage;
Uri selectedImage;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySetupProfileBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
dialog = new ProgressDialog(this);
dialog.setMessage("Updating Profile..");
dialog.setCancelable(false);
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
getSupportActionBar().hide();
binding.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 45);
}
});
binding.continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = binding.nameBox.getText().toString();
if(name.isEmpty()) {
binding.nameBox.setError("Name cannot be empty..");
return;
}
dialog.show();
if(selectedImage !=null) {
StorageReference reference = storage.getReference().child("Profiles").child(auth.getUid());
reference.putFile(selectedImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageUrl = uri.toString();
String uid = auth.getUid();
String phone = auth.getCurrentUser().getPhoneNumber();
String name = binding.nameBox.getText().toString();
User user = new User(uid, name, phone, imageUrl);
database.getReference()
.child("users")
.child(uid)
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
Intent intent = new Intent (SetupProfileActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
});
}
}
});
} else {
String uid = auth.getUid();
String phone = auth.getCurrentUser().getPhoneNumber();
User user = new User(uid, name, phone, "No Image");
database.getReference()
.child("users")
.child(uid)
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
Intent intent = new Intent (SetupProfileActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
if(data.getData() != null) {
binding.imageView.setImageURI(data.getData());
selectedImage = data.getData();
}
}
}
Check the rules in firebase console for accessing storage.
By default all authenticated users can read and write into storage.
Default rules for storage are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
You should be logged in to firebase before uploading the image.
For testing you can change the line
allow read, write: if request.auth != null;
to
allow read write;
problem was solved. Actually, In Firebase Database, I changed the location to Europe, rather then default location (US). Problem solved by changing back the location to US. Thanks !!

Firebase Anonymously authentication won work

I'm trying to upload a picture to firebase storage and the take picture is in the form of a bitmap. But I don't want any authentication at all so I have followed the Firebase tutorial on anonymous login. When running the app I don't get any errors but the picture won't upload. I don't really care if the picture taking part is perfect, right now I want to focus on the uploading onto Firebase.
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
ImageView imageView;
Button btnOpen;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
imageView = findViewById(R.id.image_view);
btnOpen = findViewById(R.id.btn_open);
textView = findViewById(R.id.textView);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.CAMERA
}, 100);
}
btnOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
Log.e("USER", currentUser.toString());
}
public void signInAnonymously() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymously();
// saveImage(takenImage);
imageView.setImageBitmap(takenImage);
}
}
private void saveImage(Bitmap inBitmap) {
long tsLong = System.currentTimeMillis() / 1000;
String ts = Long.toString(tsLong);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://savephototest.appspot.com");
StorageReference mountainImagesRef = storageRef.child(ts + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inBitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getUploadSessionUri();
Log.d("downloadUrl-->", "" + downloadUrl);
}
});
}
}
You are starting the upload of the image before the sign-in (which happens asynchronously) completes. So if you have security rules on storage that the user is signed in before they can upload, that means the write will be rejected.
Since you're leaving onFailure empty, you won't see that error. So the first step to verify if this is happening is to not ignore the error, but surface it. For example with:
public void onFailure(#NonNull Exception exception) {
throw exception;
}
If this is indeed the cause of the problem, you'll need to ensure that the upload only starts after the sign-in has been completed.
A very quick way to do that is to move the call to saveImage into the method that signs in:
public void signInAnonymouslyAndUpload() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
saveImage(takenImage);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymouslyAndUpload();
imageView.setImageBitmap(takenImage);
}
}

How to get download url for firebase storage and update firestore document?

I have been struggling to get download url for an image uploaded to firebase storage from my app.
I want to send this url to firestore databse (not realtime database).
I am setting itemImageUri to uri.toString() but in onCreate() method itemImageUrl is null and shows null in firestore. I cannot use CollectionRefernece addItemRef in onSuccess method as it gives error for all string variables: Variable is accessed from within inner class needs to be declared final.
public class AddItemActivity extends AppCompatActivity {
public class AddItemActivity extends AppCompatActivity {
public static final int PICK_IMAGE_REQUEST = 1;
public static final String TAG = "Error!";
public static final String UPLOAD_TAG = "Image uploaded";
private Uri imageUri = null;
private TextInputEditText textFieldTitle;
private TextInputEditText textFieldDesc;
private AutoCompleteTextView dropdownItemType;
private TextInputEditText textFieldAddress;
private TextInputEditText textFieldAvailability;
private MaterialButton buttonSubmitItem;
private MaterialButton buttonAddImage;
private ImageView imageViewItem;
private String itemImageUrl;
private Bitmap bitmap;
private Uri itemImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
imageViewItem = findViewById(R.id.imageView_camera);
textFieldTitle = findViewById(R.id.textField_title);
textFieldDesc = findViewById(R.id.textField_description);
dropdownItemType = findViewById(R.id.dropdown_itemType);
//Select type dropdown
String[] itemTypes = new String[] {
"Food",
"Clothing",
"Footwear"
};
ArrayAdapter<String> itemsDropdownAdpater = new ArrayAdapter<>(AddItemActivity.this, R.layout.dropdown_item_type, itemTypes);
dropdownItemType.setAdapter(itemsDropdownAdpater);
textFieldAddress = findViewById(R.id.textField_address);
textFieldAvailability = findViewById(R.id.textField_availability);
buttonAddImage = findViewById(R.id.button_addImage);
buttonSubmitItem = findViewById(R.id.button_submitItem);
buttonAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AddItemActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AddItemActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(AddItemActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
choseImage();
}
} else {
choseImage();
}
}
});
buttonSubmitItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitItem();
}
});
}
private void choseImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(AddItemActivity.this);
}
private void submitItem() {
String title = textFieldTitle.getText().toString();
String desc = textFieldDesc.getText().toString();
String type = dropdownItemType.getText().toString();
String address = textFieldAddress.getText().toString();
String availability = textFieldAvailability.getText().toString();
if (title.trim().isEmpty() ||
desc.trim().isEmpty() ||
type.trim().isEmpty() ||
availability.trim().isEmpty()) {
Toast.makeText(this, "Fields cant be empty", Toast.LENGTH_SHORT).show();
return;
}
handleUpload(bitmap);
CollectionReference addItemRef = FirebaseFirestore.getInstance()
.collection("ItemList");
addItemRef.add(new ItemListModel(title, desc, type, address, availability, itemImageUrl));
Toast.makeText(this, "Item added", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
imageViewItem.setImageURI(imageUri);
imageViewItem.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageViewItem.getDrawable();
bitmap = drawable.getBitmap();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void handleUpload(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final StorageReference reference = FirebaseStorage.getInstance().getReference()
.child("itemImages")
.child(System.currentTimeMillis() + ".jpeg");
reference.putBytes(baos.toByteArray())
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
getItemImageUrl(reference);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "onFailure: ", e.getCause());
}
});
}
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
}
});
}
}
Determining the download URL requires a call to the servers, which means it happens asynchronously. For this reason, any code that needs the download URL needs to be inside the onSuccess of getDownloadURL() or be called from there.
So:
private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();
... here you can write itemImageUrl to the database
}
});
}
Also see:
How to get the download url from Firebase Storage?
In NodeJS, to get a link for a document stored in Firebase Storage.
const options = {
version: 'v2', // defaults to 'v2' if missing.
action: 'read',
expires: Date.now() + 1000 * 60 * 60, // one hour
};
let url = storage
.bucket(bucketname)
.file(filename)
.getSignedUrl(options);
First upload the file to the Storage, then call your upload method to the database on the addOnCompleteListener :
final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(uriList.get(i)));
uploadTask = fileReference.putFile(uriList.get(i));
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful() && task.getException() != null) {
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();
if(downloadUri != null) {
itemImageUrl = downloadUri.toString()
// create your object
// upload your object to the database here
}
}
}
});

how to get url of an uploaded image in firebase storage v16.0.1 [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command getDownloadUrl, but I believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage. where to add storagerefernce.downloadUrl().
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (ImageButton) findViewById(R.id.btnChoose);
imageView = (ImageView) findViewById(R.id.imgView);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
chooseImage();
}
});
}
public void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null )
{
filePath = data.getData();
imgname = filePath.getLastPathSegment();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
uploadImage();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage()
{
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ imgname);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.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 can try this way.
val ref = mStorageReference?.child("images/mMobileNumber.jpg")
val uploadTask = ref?.putFile(Uri.fromFile(File(mImagePath)))
uploadTask?.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>>
{ task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation ref.downloadUrl
})?.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
mTempDatabaseReference?.child("image")?.setValue(downloadUri.toString())
} else {
// Handle failures
// ...
}
}

Categories

Resources