Reputation: 1837
I have the following code in order to display an image inside ImageView
once I choose from gallery/took a picture:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
FixBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
ShowSelectedImage.setImageBitmap(FixBitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ProfileActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
FixBitmap = (Bitmap) data.getExtras().get("data");
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
Now, I had like this image to be saved inside my FirebaseStorage under the uid
of the current user.
So I know I should use something as:
String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
However, how do I make this upload inside my storage? My final goal is that once the user login it will automatically display the profile picture from the storage and if there is no picture or the user took a new pic, it will update the one inside the storage.
I had problems also with type since putBytes
required BytesArray
and the results I had are Bitmap
or so.
Thank you.
Upvotes: 1
Views: 375
Reputation: 6919
Following code will help you to store image under images folder with userid of current user. You have image location so Firebase will pick image from storage.
uploadImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(contentURI != null) {
StorageReference childRef = storageRef.child("/images/"+uid+".jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(contentURI);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
Declare variable :
StorageReference storageRef;
and in onCreateView :
storageRef = storage.getReference();
Make it publicly declared or it will throw an error again
Upvotes: 1