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);
}
}
Related
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())
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 !!
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.
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
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
// ...
}
}