I am trying to upload the image using firebase but I am not able to do so. I am not getting what is going wrong while uploading. Here is the code:
private void saveUserInformation() {
mCustomerDatabase.updateChildren(userInfo);
if (resultUri != null) {
final StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
assert bitmap != null;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("SA", "Fail1");
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("profileImageUrl", uri.toString());
mCustomerDatabase.updateChildren(newImage);
Log.d("SA", "Success");
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("SA", "Fail2");
finish();
}
});
}
});
} else {
finish();
}
}
The StorageException occurs and it is not uploaded in the firebase console as well. Help appreciated!!
Define Variable
private static int GALLERY_PICK = 1 ;
private Uri imageUri;
private Button uploudBtn;
private ImageView profileImageView;
imageView, when pressed, chooses the image from the gallery.
profileImageView.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 , GALLERY_PICK);
}
});
onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK && data != null)
{
imageUri = data.getData();
profileImageView.setImageURI(imageUri);
}
}
and then the upload code for image(button )
uploudBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(imageUri != null)
{
final StorageReference filePath = userProfileImageRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
final UploadTask uploadTask = filePath.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();
}
downloadUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadUrl = task.getResult().toString();
Toast.makeText(MainActivity.this, "Your profile Info has been updated", Toast.LENGTH_SHORT).show();
}
}
});
**Remark you should cast uploudBtn , profileImageView in OnCreate methods **
profileImageView = findViewById(R.id.imageView);
uploudBtn = findViewById(R.id.button);
Related
I am unable to fetch the uploaded image file from the firebase storage because the database stores the url in a public unguessable url form and I cannot seem to figure it out, what is wrong with my code?
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1,1)
.start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading");
mProgressDialog.setMessage("Please Wait While The Image Is Being Uploaded");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
final String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Uploaded Successfully", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
}
First you can convert your image in bitmap stream and then you can upload it on firebase storage and get downloadable link also easily. You can do something like this below:
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byt = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(byt);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
TastyToast.makeText(getApplicationContext(),"Error:"+e.getMessage(),TastyToast.LENGTH_LONG,
TastyToast.ERROR).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(taskSnapshot.getMetadata() != null){
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
downloadUrl = Uri.parse(uri.toString());
// In downloadUri variable you will get your
image downloadable link
}
});
}
}
});
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
I am following a series of videos on youtube from the channel CodingInFlow. They are a bit Outdated, 2017 is long time ago. The Video Series is great and I followed up the 4th video no problem, except one deprecated function that was easy enough to resolve. The file uploads to the Firebase Storage, but it doesn't show up in the Real Time Database
Main Class
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button mButtonChooseImage;
Button mButtonUpload;
TextView mTextViewShowUploads;
EditText mEditTextFileName;
ImageView mImageView;
ProgressBar mProgressBar;
Uri mImageUri;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getStorage().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
//assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
My question is, is it my mistake that I missed something (I followed the video exactly, and checked the code on the channel's website), or is it that the functionality shifted and something needs to be added?
The reason I ask is that the app works in the video, including the function that the checks for duplicate uploads, but in my reproduction, that function only works while the picture actually uploads, so there has been some shifting, but I don't even know where to start research, so I'm starting here.
This is how I did mine. This code saves the image to the storage and to the firebase realtime database under the child "profile image" as a link.
public class Registration3 extends AppCompatActivity {
Button elFin;
CircleImageView ProfileImage;
private DatabaseReference UsersRef;
private FirebaseAuth mAuth;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration3);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
elFin = findViewById(R.id.btn_dd);
ProfileImage = findViewById(R.id.profile_imageUp);
UsersRef = FirebaseDatabase.getInstance().getReference().child("DriversInformation").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
ProfileImage.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, Gallery_Pick);
}
});
elFin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Registration3.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Gallery_Pick && 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) {
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.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(Registration3.this, "Image Uplaoded", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(Registration3.this, Registration3.class);
startActivity(selfIntent);
Toast.makeText(Registration3.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Registration3.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(Registration3.this, "Error: ", Toast.LENGTH_SHORT).show();
}
}
}
}
I am trying to create an app using firebase storage service. I have a function that saves an image from device local storage, uses the URI of the picture to save it to firebase. When trying to upload the image to firebase server I get "object does not exist at location", probaby meaning there is a problem which my URI.
I am adding the entire activity so you can see what is going on -
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int PICK_IMAGE_REQUEST = 1;
public static final int DELAY_MILLIS = 5000;
private Button buttonChooseImage, buttonUpload;
private TextView textViewShowUpload;
private EditText editTextFileName;
private ImageView imageView;
private ProgressBar progressBar;
private Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChooseImage = findViewById(R.id.button_choose_image);
buttonUpload = findViewById(R.id.button_upload);
textViewShowUpload = findViewById(R.id.text_view_show_uploads);
editTextFileName = findViewById(R.id.edit_text_file_name);
imageView = findViewById(R.id.image_view);
progressBar = findViewById(R.id.progress_bar);
buttonChooseImage.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
textViewShowUpload.setOnClickListener(this);
storageReference = FirebaseStorage.getInstance().getReference("uploads");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_choose_image:
openFileChooser();
break;
case R.id.button_upload:
uploadFile();
break;
case R.id.text_view_show_uploads:
break;
}
}
private String getFileExtension(Uri uri) {
ContentResolver cr = getContentResolver();
MimeTypeMap mine = MimeTypeMap.getSingleton();
return mine.getExtensionFromMimeType(cr.getType(uri));
}
private void uploadFile() {
if (imageUri != null) {
StorageReference fileRefrence = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
fileRefrence.putFile(imageUri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, DELAY_MILLIS);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(editTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, 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());
progressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}
}
Am I implementing URI incorrectly?
edit -
tryed this solution from comments, yet still getting the same error -
private void uploadFile() {
if (imageUri != null) {
StorageReference fileReference = storageReference.child("images/" + imageUri.getLastPathSegment());
UploadTask uploadTask = fileReference.putFile(imageUri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, DELAY_MILLIS);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(editTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, 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());
progressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
For me Uploading was possible with this code. I got this at https://www.youtube.com/watch?v=lPfQN-Sfnjw&list=PLrnPJCHvNZuBf5KH4XXOthtgo6E4Epjl8&index=4 in the comment section. Also set the authentication in your firebase storage to true
private void uploadFile(){
if(mImageUri!=null){
storageReference.putFile(mImageUri).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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
Uri downloadUri = task.getResult();
Log.e("TAG", "then: " + downloadUri.toString());
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
downloadUri.toString());
databaseReference.push().setValue(upload);
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(this, "Please upload image!", Toast.LENGTH_SHORT).show();
}
}
This is the code what i have used for my project and its working...
Also make sure that
you have make rules public on firebase storage
added the permission in your manifest file for access phone storage and internet
added all required dependencies for firebase storage access
StorageReference storageReference;
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference refStorage = storageReference.child("images/"+uri.getLastPathSegment());
UploadTask uploadTask = refStorage.putFile(uri);
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 new Exception("task is not succeeded");
} return refStorage.getDownloadUrl();
}//end of throws Exception method
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downUri = task.getResult();
} else {
// Handle failures
// ...
Log.d("<<<<<<<<", "<<<<<<<<<<<<<<<<<<<< not uplooaded ");
}
}//end of onComplete()for getting download uri
});
Replace the following code:
StorageReference fileRefrence = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
with this:
StorageReference fileRefrence = storageReference.child(imageUri.getLastPathSegment());
Try this code
StorageReference imageReference = storageReference.child("uploads");
UploadTask uploadTask = imageReference.putFile(imageuri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(verify.this, "Upload failed!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
i am working on the a social app where the user can upload their image on their feeds but when the user is picking up the image ,the image less than 2 mb are getting picked up and are successfully uploaded to the firebase but when the user uploads the image more than 2mb the app crashes. what can be done to compress the image ..
postactivity.java
private Toolbar mToolbar;
private ImageButton SelectPostImage;
private Button UpdatePostButton;
private ProgressDialog loadingBar;
private EditText PostDescription;
private static final int Gallery_pick = 1;
private Uri ImageUri;
private String Description;
private StorageReference PostsImagesReference;
private DatabaseReference usersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,current_user_id, postRandomName, downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
SelectPostImage = (ImageButton)findViewById(R.id.select_post_image);
UpdatePostButton = (Button) findViewById(R.id.update_post_button);
PostDescription = (EditText)findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
SelectPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
Description = PostDescription.getText().toString();
if (ImageUri == null){
Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(Description)){
Toast.makeText(this,"Please write something here",Toast.LENGTH_SHORT).show();
}else {
loadingBar.setTitle(" Add New Post");
loadingBar.setMessage("Please wait, while we updating your new post");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH: mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this,"Image is sucessfully uploaded to storage",Toast.LENGTH_LONG).show();
SavingPostInformationToDatabase();
}else{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this,"Error Occured:" + message,Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase() {
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String userfullname = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid",current_user_id);
postsMap.put("date",saveCurrentDate);
postsMap.put("time",saveCurrentTime);
postsMap.put("description",Description);
postsMap.put("postimage",downloadUrl);
postsMap.put("profileimage",userProfileImage);
postsMap.put("fullname",userfullname);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this,"Your New Post is Updated Sucessfully",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(PostActivity.this,"Error Occured while updating your post .please try again ",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_pick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_pick && resultCode == RESULT_OK && data != null){
ImageUri = data.getData();
SelectPostImage.setImageURI(ImageUri);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainintent = new Intent(PostActivity.this,MainActivity.class);
startActivity(mainintent);
}
}
byte[] thumb_byte_data;
Uri resultUri = ImageUri;
//getting imageUri and store in file. and compress to bitmap
File file_path = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(75)
.compressToBitmap(file_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumb_byte_data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
You can then upload to firebase with the this code:
final UploadTask uploadTask = bytepath.putBytes(thumb_byte_data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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 filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(yourimageuri, width, height, true);// the uri you got from onactivityresults
You can also view this thirdparty lib to compress your image Click Here
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
companyImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Pick Comapany Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference =
FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
//assign download url in hashmap to upadate database reference
update_hashMap.put("Image",downloadUrl);
//update database children here
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}
I am trying to Compress an Image before Uploading it to Firebase Storage using SiliCompressor library , but it seems not working , the ProgressDialog doesn't stop. What i first did was to pick the Image from the Gallery into an ImageButton by clicking an ImageButton. Below is my code.
imageSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
---------------------------------------------------------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
imageUri = data.getData();
// imageSelect.setImageBitmap(BitmapFactory.decodeFile(imageSelectFile.getAbsolutePath()));
// Compressor com = Compressor.getDefault(this).compressToFile(imageFile);
// imageSelect.setImageURI(imageUri);
Picasso.with(c).load(imageUri).fit().into(imageSelect);
}
}
So now am having a Method startPosting() which Uploads data By a click of Button to Firebase Storage.
Below is my code.
private void startPosting() {
mProgress.setMessage("Uploading Image...");
//Compressing an Image ....
String stringUri= imageUri.toString();
Uri uri_image_final;
//String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri);
String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri, true);
uri_image_final = Uri.parse(filePath);
System.out.println("Whats here :" +
""+ uri_image_final);
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && filePath != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
filepath.putFile(uri_image_final).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
DatabaseReference c = mDatabase.push();
newPost.child("EventTitle").setValue(title_val);
newPost.child("EventDescription").setValue(desc_val);
newPost.child("EventImage").setValue(downloadUri.toString());
newPost.child("PostId").setValue(c);
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
);
} else if (TextUtils.isEmpty(title_val) && TextUtils.isEmpty(desc_val) && imageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
filepath.putFile(uri_image_final).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("EventTitle").setValue("");
newPost.child("EventDescription").setValue("");
newPost.child("EventImage").setValue(downloadUri.toString());
mProgress.dismiss();
// startActivity(new Intent(PostActivity.this, MainActivity.class));
Intent load= new Intent(PostActivity.this,MainActivity.class);
load.putExtra(eventname,eventname);
startActivity(load);
}
}
);
}
else if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && imageUri== null){
Toast.makeText(getApplicationContext(),"Please insert an Image and Upload ! ",Toast.LENGTH_LONG).show();
}
}
Now if you see in that Method , my essence was to Compress an Image which is loaded in the ImageButton, then Afterwards it Uploads to firebase.
This is the line of Silicon Compressor which tries to compress an image loaded in the ImageButton.
String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri, true);
I got this lib from this link of Github.
https://github.com/Tourenathan-G5organisation/SiliCompressor
So where am i wrong please because the Image is not Uploading but i want it to Upload while it's compressed.
Here is what I have written, you can try it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Constants.PICK_USER_PROFILE_IMAGE) {
if (resultCode == RESULT_OK) {
Bitmap bmp = ImagePicker.getImageFromResult(this, resultCode, data);//your compressed bitmap here
startPosting(bmp);
}
}
}
}
Your startPosting method should be like this
private void startPosting(Bitmap bmp) {
byte[] data = bmp.toByteArray();
mProgress.setMessage("Uploading Image...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && filePath != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
UploadTask uploadTask = filepath.putBytes(data);
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) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
DatabaseReference c = mDatabase.push();
newPost.child("EventTitle").setValue(title_val);
newPost.child("EventDescription").setValue(desc_val);
newPost.child("EventImage").setValue(downloadUri.toString());
newPost.child("PostId").setValue(c);
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
});
} else if (TextUtils.isEmpty(title_val) && TextUtils.isEmpty(desc_val) && imageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
UploadTask uploadTask = filepath.putBytes(data);
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) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("EventTitle").setValue("");
newPost.child("EventDescription").setValue("");
newPost.child("EventImage").setValue(downloadUri.toString());
mProgress.dismiss();
// startActivity(new Intent(PostActivity.this, MainActivity.class));
Intent load= new Intent(PostActivity.this,MainActivity.class);
load.putExtra(eventname,eventname);
startActivity(load);
}
});
}
else if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && imageUri== null){
Toast.makeText(getApplicationContext(),"Please insert an Image and Upload ! ",Toast.LENGTH_LONG).show();
}
}
Below is the class ImagePicker that have series of methods to do your work
public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400; // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Bitmap getImageFromResult(Context context, int resultCode,
Intent imageReturnedIntent) {
Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
Bitmap bm = null;
File imageFile = getTempFile(context);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
boolean isCamera = (imageReturnedIntent == null ||
imageReturnedIntent.getData() == null ||
imageReturnedIntent.getData().equals(Uri.fromFile(imageFile)));
if (isCamera) { /** CAMERA **/
selectedImage = Uri.fromFile(imageFile);
} else { /** ALBUM **/
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "selectedImage: " + selectedImage);
bm = getImageResized(context, selectedImage);
int rotation = getRotation(context, selectedImage, isCamera);
bm = rotate(bm, rotation);
}
return bm;
}
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
/**
* Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
**/
private static Bitmap getImageResized(Context context, Uri selectedImage) {
Bitmap bm = null;
int[] sampleSizes = new int[]{5, 3, 2, 1};
int i = 0;
do {
bm = decodeBitmap(context, selectedImage, sampleSizes[i]);
Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
i++;
} while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
return bm;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
Log.d(TAG, "Image rotation: " + rotation);
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static int getRotationFromGallery(Context context, Uri imageUri) {
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor == null) return 0;
cursor.moveToFirst();
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
return cursor.getInt(orientationColumnIndex);
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return bmOut;
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
}
The ImagePicker Class have all the methods of handling compression as well as rotation of image.
Hope it will help
Thanks to this link for uploading file ref
Uploading files on firebase
I have done this way:
private void startPosting() {
mProgress.setMessage(getString(R.string.downloading_route));
final String titleVal = mRouteTitle.getText().toString().trim();
final String descVal = mRouteDesc.getText().toString().trim();
if (!TextUtils.isEmpty(titleVal) && !TextUtils.isEmpty(descVal) && mImageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("Route images").child(mImageUri.getLastPathSegment());
//compress image
mSelectImage.setDrawingCacheEnabled(true);
mSelectImage.buildDrawingCache();
Bitmap bitmap = mSelectImage.getDrawingCache();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = mDatabase.push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("title").setValue(titleVal);
newPost.child("desc").setValue(descVal);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(AddRouteActivity.this, MainActivity.class));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
});
}
}
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
ImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Pick Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
**//assign download url in hashmap to upadate database reference**
update_hashMap.put("Image",downloadUrl);
**//update database children here**
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}