Downloading Photo from Firebase Storage - android

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())

Related

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);
}
}

Trying to get image from firebase so that user can set profile image but its blank

Im trying to allow users to click on the image item and choose a picture from their galley. this picture should then be pushed to firebase and added to the image view automatically but it is showing up blank after I close the application. I have tried numerous methods but cant seem to get it working. here is where i implement everything:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ImageView imageView;
public static final int IMAGE_CODE = 1;
Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
FirebaseUser user;
String userid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) headerView.findViewById(R.id.profilepic);
user = FirebaseAuth.getInstance().getCurrentUser();
userid = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference("Images");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads").child(userid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openimage();
}
});
profileImage();
}
private void profileImage(){
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void openimage() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGE_CODE);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
// You don't have permission
checkPermission1();
} else {
// Do as per your logic
}
}
if (requestCode == IMAGE_CODE && resultCode == RESULT_OK && null != data && data.getData() != null) {
imageUri = data.getData();
Glide.with(this).load(imageUri).into(imageView);
fileUploader();
}
}
private String getFileExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void fileUploader(){
if(imageUri != null){
StorageReference reference = storageReference.child(userid + ".jpeg");
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) {
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
profileImage();
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
;;
}
});
}else{
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
Database Structure
Edit:
2020-05-03 15:55:51.232 25230-25407/com.example.carcrashdetection E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-05-03 15:55:51.235 25230-25407/com.example.carcrashdetection E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Also the image is in a navigation drawer and should be unique to each user. Can someone please tell me where I am going wrong?
You can do it like this:
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload = new Upload(uri.toString());
String uploadId = databaseReference.child(userid).push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
});
Firebase Storage docs
And there is a problem in this line:
Glide.with(getApplicationContext()).load(upload).into(imageView);
upload is an object. You should use upload.getUploadUri()
if(dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
Upload upload = ds.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
You always see last uploaded image this way. If a user has an image you don't need to use uploadId.
Profile image:
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload);
and:
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
more useful for you.

uri.tostring() on a null object reference

public class profile_activity extends AppCompatActivity implements View.OnClickListener {
private static final int CHOOSE_IMAGE = 101;
ImageView imageViewprofile;
EditText editTextName;
Uri uriProfile;
ProgressBar progressbar;
String profileImageUrl;
Button buttonSave;
FirebaseAuth mauth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_activity);
editTextName = (EditText) findViewById(R.id.editTextName);
imageViewprofile = (ImageView) findViewById(R.id.imageViewProfile);
progressbar = (ProgressBar) findViewById(R.id.progressBar2);
buttonSave =findViewById(R.id.buttonSave);
mauth = FirebaseAuth.getInstance();
loadUserInfo();
imageViewprofile.setOnClickListener(this);
buttonSave.setOnClickListener(this);
}
private void loadUserInfo() {
if(mauth.getCurrentUser() != null){
FirebaseUser user = mauth.getCurrentUser();
if(user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl().toString()).into(imageViewprofile);
}
if (user.getDisplayName() != null) {
editTextName.setText(user.getDisplayName());
}
Toast.makeText(getApplicationContext(),"load user info chal rha hai",Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
if(mauth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,MainActivity.class));
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageViewProfile:
showImageChooser();
break;
case R.id.buttonSave:
saveinfo();
break;
}
}
private void saveinfo(){
uploadImageToFirebaseStorage();
String name = editTextName.getText().toString();
if(name.isEmpty()) {
editTextName.setError("Name cannot be empty!");
editTextName.requestFocus();
return;
}
if(profileImageUrl== null){
Toast.makeText(getApplicationContext(),"User profile nalla h 1",Toast.LENGTH_SHORT).show();
}
FirebaseUser user = mauth.getCurrentUser();
if(user != null && profileImageUrl != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
setDisplayName(name).
setPhotoUri(Uri.parse(profileImageUrl)).
build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
}
}
});
}
if (user==null){
Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CHOOSE_IMAGE && resultCode==RESULT_OK && data != null && data.getData() != null){
uriProfile = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfile);
imageViewprofile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressbar.setVisibility(View.GONE);
//profileImageUrl = profileImageRef.getDownloadUrl().toString();
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImageUrl = uri.toString();
if(profileImageUrl== null){
Toast.makeText(getApplicationContext(),"User profile nalla h",Toast.LENGTH_SHORT).show();
}
Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressbar.setVisibility(View.GONE);
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Profile Image"),CHOOSE_IMAGE);
}
}
My aim is to load the information on the profile if it already saved.
But it's not saving due the following:
The profileImageUrl is null but only in saveinfo method, it's getting value in uploadImageToFirebaseStorage and still it's null in saveinfo method, I have made it double sure that profilimageurl is a global variable.
I don't understand this.
I'm pretty new to firebase. Please help me out.
Here's the whole code.
As zgc7009 pointed out the problem is occurring due to asynchronous call , when you call
uploadImageToFirebaseStorage();
you assume that the method will return after uploading the image and setting a url to profileImageUrl but no , it returns immediately after setting your listeners, then control reaches if(profileImageUrl== null) which is true because the image is not uploaded yet and your listener callback is not executed to set the profileImageUrl
then the control reaches if(user != null && profileImageUrl != null) which is false for the same reason, SO NOW YOU GET IT , RIGHT?
FIX
if i am not wrong you want to show new user image when he changes the profile but that only can happen when the image is uploaded that means onSuccessLisener() on putFile() is executed that means that code depends on the callback so move it in the callback .
Move the code from saveInfo() to uploadImageToFirebaseStorage(); like that
private void uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressbar.setVisibility(View.GONE);
//profileImageUrl = profileImageRef.getDownloadUrl().toString();
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImageUrl = uri.toString();
FirebaseUser user = mauth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
setDisplayName(name).
setPhotoUri(Uri.parse(profileImageUrl)).
build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
}
}
});
}
if (user==null){
Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
}
Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressbar.setVisibility(View.GONE);
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
**note** i removed some `if` conditions because those were guranteed to be true,you will also need to make some variable final because now those are getting used within the inner class
Alternatively
uploadImageToFirebaseStorage(); make this method return the UploadTak if you do want to move code from saveInfo something like below
private Task<UploadTask> uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
return profileImageRef.putFile(uriProfile)
}
}
Now set the listener in the saveInfo()
I also encourage you to break the code into methods because code now looks messy, have a good day Himanjli

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
// ...
}
}

Firebase - Associating Pictures to Users?

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);

Categories

Resources