Upload succeeded if imageUri was in this form.
content://com.android.providers.media.documents/document/image%3A12305
But this form failed
/document/image:10674
And I got this Toast message.
"An unknown error occurred, please check the HTTP result code and inner exception for server response."
I'd appreciate it if you could give me any hints.
What I tried
1.Get Image from gallery
Uri imageUri;
StorageTask uploadTask;
StorageReference storageReference;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File compressedImageFile; //for compress library : https://github.com/zetbaitsu/Compressor
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
try {
compressedImageFile = new Compressor(getContext()).compressToFile(new File(selectedImageUri.getPath()));
imageUri = data.getData(); //this works well but uploaded original size.
// imageUri =Uri.fromFile(compressedImageFile); //fail
// imageUri= Uri.fromFile(new File(compressedImageFile.toURI().getPath())); //fail
// imageUri= Uri.parse(new File(compressedImageFile.getPath()).toString()); //fail
if (uploadTask != null && uploadTask.isInProgress()) {
Toast.makeText(getContext(), "Upload in preogress", Toast.LENGTH_SHORT).show();
} else {
uploadImage();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.uploadImage();
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
uploadTask = fileReference.putFile(imageUri);
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String mUri = downloadUri.toString();
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL", "" + mUri);
reference.updateChildren(map);
} else {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
По пробуйте это
StorageReference riversRef =
storageRef.child("images/"+imageUri.getLastPathSegment());
uploadTask = riversRef.putFile(imageUri);
// Register observers to listen for when the download is done or if it
//fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size,
//content-type, etc.
}
});
add this code into your file :-
StorageReference storageReference;
storageReference = storage.getReference();
final StorageReference ref = storageReference.child("images/" + UUID.randomUUID());
ref.putFile(your file path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot> () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri imageUrl{
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(IndivudualChatActivity.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());
}
});
Related
I want to save image url in real-time database but none of the solutions that I tried is solve the problem, the code that I wrote it saving the image in firebase storage but I want to save the image url in real-time database, so can anyone help?
this code just save the image in firebase storage
private Button btn_upload,btn_choose;
private ImageView imageView;
private Uri filepath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_choose= (Button) findViewById(R.id.btn_choose);
btn_upload= (Button) findViewById(R.id.btn_upload);
imageView= (ImageView) findViewById(R.id.myImage);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
}
// choose image function code
private void uploadImage() {
if(filepath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progres = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progres+"%");
}
}) ;
} }
I want to store image in real-time database
You can request download URL for the file after uploading finishes.
Then Add the URL to Real-time Database
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//You will get donwload URL in uri
Log.d(TAG, "Download URL = "+ uri.toString());
//Adding that URL to Realtime database
mDatabase.child("imageUrl").setValue(uri.toString());
}
});
}
})
#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();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage() {
name = txtname.getText().toString();
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ name);
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+"%");
}
});
}
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
I'm trying to upload some images to firestore storage and put the image URL to firebase database. The images are uploading successfully but the image URLs aren't being added to the database. The problem that I think might be causing this is that the image URL is being added to the Hashmap after uploading the image but the database upload process isn't waiting for the URL instead, adding all other HashMap keys to the database before the Upload task returns the URL. This way all other keys get added to the database but not the Image URLs. In the below code product id is being added successfully to the database, also if I leave any image unselected its url alse gets added as empty to the database which is working fine but if I select an image to upload, The hashmap to database upload finishes even before getting the uploaded image URL.
public class AddProductDataActivity extends AppCompatActivity {
String productId;
EditText productIdEditText;
ImageView addProductImage3;
Button addProductSubmit;
final int IMAGE3_REQUEST = 30;
Uri image3LocationPath;
StorageReference objectStorageReference;
FirebaseFirestore objectFireBaseFireStore;
Map<String, String> objectMap = new HashMap<>();
StorageReference img3Store;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product_data);
brandNameEditText =(EditText)
addProductImage3 = (ImageView) findViewById(R.id.add_product_image3);
objectStorageReference =
FirebaseStorage.getInstance().getReference("images");
objectFireBaseFireStore = FirebaseFirestore.getInstance();
addProductImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent objectIntent = new Intent();
objectIntent.setType("image/*");
objectIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(objectIntent, IMAGE3_REQUEST);
}
});
addProductSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productId = productIdEditText.getText().toString();
if(image3LocationPath != null)
{
final String image3Name = productId + "_image3." + getExtension(image3LocationPath);
img3Store = objectStorageReference.child(image3Name);
UploadTask imageUploadTask = img3Store.putFile(image3LocationPath);
imageUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if(!task.isSuccessful())
{
Toast.makeText(AddProductDataActivity.this, "Task Unsuccessful", Toast.LENGTH_SHORT).show();
}
return img3Store.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful())
{
String image_3_url = task.getResult().toString();
objectMap.put("image3_url",image_3_url);
}
else
{
Toast.makeText(AddProductDataActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
objectMap.put("image3_url","");
}
objectFireBaseFireStore.collection("images").document(productId).set(objectMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(AddProductDataActivity.this, "Product Added Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddProductDataActivity.this, "Error in Adding Product. Please Try Again.\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 30:
try
{
if(resultCode == RESULT_OK && data != null && data.getData() != null)
{
image3LocationPath = data.getData();
Bitmap objectBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image3LocationPath);
addProductImage3.setImageBitmap(objectBitmap);
}
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
private String getExtension(Uri uri){
try
{
ContentResolver objectContentResolver = getContentResolver();
MimeTypeMap objectMimeTypeMap = MimeTypeMap.getSingleton();
return objectMimeTypeMap.getExtensionFromMimeType(objectContentResolver.getType(uri));
}
catch (Exception e)
{
Toast.makeText(AddProductDataActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
Your code
objectFireBaseFireStore.collection("images").document(productId).set(objectMap)
executes before
objectMap.put("image3_url",image_3_url)
Which means when you are setting your url, your objectMap does not have the key image3_url
Try to set values to database inside onComplete() or use different workaround to set only the url.
You forgot to add your HashMap to Database Reference of Firebase.
This is reference from my current project code.
private void uploadVideo() {
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference riversRef = mStorageRef.child(Constants.STORAGE_PATH + "/" + mFinalUploadUri.getLastPathSegment());
riversRef.putFile(mFinalUploadUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return riversRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseFirestore database = FirebaseFirestore.getInstance();
String mSelectedCategory = binding.categorySpinner.getSelectedItem().toString();
DocumentReference newDocumentReference = database.collection(PENDING_PATH).document();
VideoModel videoModel = new VideoModel();
videoModel.setDocumentId(newDocumentReference.getId());
videoModel.setTitle(mTitle);
videoModel.setCategory(mSelectedCategory);
//videoModel.setTime(FieldValue.serverTimestamp());
videoModel.setUrl(downloadUri != null ? downloadUri.toString() : null);
newDocumentReference.set(videoModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
binding.progressBar.setVisibility(View.GONE);
binding.button.setVisibility(View.VISIBLE);
binding.videoView.setVisibility(View.GONE);
selectedUri = null;
Toast.makeText(AdminVideoUploadActivity.this, R.string.uploaded_successfully, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AdminVideoUploadActivity.this, R.string.failed_to_upload, Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
Now you can check code and find where you have done mistake. Just add lines of code of inserting in database.
Thank you.
I want to upload my picture into my image into my database and save it as a url and then call it to my circle image view as a profile picture. But it's not being saved as a url and it's not showing up as a profile.
I have tried switching my code up. Invalidating and restarting android studio. Cleaning and rebuilding the project countless amounts of times. Wiped the data from my phone and my emulator. And I watched a bunch of videos and read answers here and elsewhere.
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void InitializeFields() {
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode==RESULT_OK && data!=null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();
String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if(TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please enter your user name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please write your status...", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
} else{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error:", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Update your info", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
I want to upload the image into my Firebase database using an image URL and then display it in my circle image view as a profile picture.
EDIT !!
I uploaded that code and imported continuation but this is what I see now.
Code2
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
progressDialog.setCancelable(false);
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(AdminPanel.this, "Uploaded", Toast.LENGTH_SHORT).show();
// Upload upload=new Upload( databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey()).setValue(taskSnapshot.))
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference url= databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey());
Upload upload=new Upload( uri.toString());
url.setValue(upload);
Intent Refresh=new Intent(AdminPanel.this, AdminPanel.class);
startActivity(Refresh);
finish();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AdminPanel.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+"%");
}
});
}
}
I think the update should be like this:
final StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return filePath.getDownloadUrl();
}}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();
String downloadUrl = task.getResult().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
I have created a profile for my app. I want the user to be able to select an image from stored images on phone which then also updates profile pic into firebase. I am able to change to the profile pic and place into imageView, however when i close profile and then return the image has not saved onto the profile but uploaded to firebase.
Code for updating profile pic:
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);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriProfileImage = data.getData();
//try {
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
//imageView.setImageBitmap(bitmap);
Glide.with(this)
.load(uriProfileImage)
.apply(new RequestOptions()
.placeholder(R.drawable.icon_camera))
.into(imageView);
uploadImageToFirebaseStorage();
//} catch (IOException e) {
// e.printStackTrace();
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Upload user information:
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
Load user information
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
I am uploading a pdf to Firebase Storage and want to get its download url. I am using the following code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1212:
if (resultCode == RESULT_OK) {
String FilePath = data.getDataString();
t.setText(FilePath);
Uri pdfuri = data.getData();
final StorageReference mp = mpdf.child("pdf").child(random()+".pdf");
mp.putFile(pdfuri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.modifySingle(parent,ch,download_url);
Toast.makeText(modifypdf.this,download_url , Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(modifypdf.this,"Faild" , Toast.LENGTH_SHORT).show();
}
}
});
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
the result of the line
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
is
"com.google.android.gms.tasks.zzu#7f93358"
not the right url
the solution of the problem is to use upload task and in its in Complete Listener you write your code get the result of the task as a Uri and cast it into String
final String name = random() + ".pdf";
dp = mpdf.child("pdf").child(name);
UploadTask uploadTask = dp.putFile(pdfuri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return dp.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
tt = title.getText().toString();
Uri downloadUri = task.getResult();
String download_url = downloadUri.toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.updateChild(parent, ch, "url",download_url,tt);
GeologicDatabase.updateChild(parent,ch,"name",name,tt);
Toast.makeText(addpdf.this, download_url, Toast.LENGTH_SHORT).show();
finish();
} else {
// Handle failures
// ...
}
}
});
getDownloadUrl() doesn't return a URL. As you can see from the javadoc, it returns a Task that yields the URL. You'll have to wait on this Task to complete in order to get the final URL.
//Try this one
Task<Uri> newTask = task.getResult().getMetadata().getReference().getDownloadUrl();
newTask.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
yourUriVariable= uri;
}
});