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
}
}
});
}
});
}
Related
I have successfully uploaded the media in the firebase but i'm unable to retrieve it. apparently it shows that the media_problem is pointing to a null object. below is my code.
This is my code to retrieve:
this.view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "TOO FAST! TRY AGAIN", Toast.LENGTH_LONG);
try {
Dash_agri.this.firestore.collection("problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete( Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
Dash_agri.this.records.clear();
Iterator it = ((QuerySnapshot) task.getResult()).iterator();
while (it.hasNext()) {
QueryDocumentSnapshot document = (QueryDocumentSnapshot) it.next();
Dash_agri.this.single_ID = document.getId();
Dash_agri.this.single_name = (String) document.get("NAME_problems");
Dash_agri.this.single_phone = (String) document.get("PHONE_problems");
Dash_agri.this.single_description = (String) document.get("DESCRIPTION_problems");
Dash_agri.this.single_URL = (String) document.get("MEDIA_problems");
String view_media = "Touch to view media";
new SpannableString(view_media).setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
}, 0, 9, 33);
Dash_agri.this.record_id.add(Dash_agri.this.single_ID);
ArrayList<String> arrayList = Dash_agri.this.records;
StringBuilder sb = new StringBuilder();
sb.append("QUERY#");
sb.append(Dash_agri.this.single_ID);
sb.append(" by ");
sb.append(Dash_agri.this.single_name);
sb.append("\n");
sb.append(Dash_agri.this.single_description);
sb.append("\n\n");
sb.append(view_media);
arrayList.add(sb.toString());
}
}
}
});
} catch (Exception e) {
Toast.makeText(Dash_agri.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
Dash_agri.this.listView.setAdapter(new ArrayAdapter<>(Dash_agri.this.getApplicationContext(), R.layout.simple_list_item_1, Dash_agri.this.records));
}
});
This is my code to upload:
public class Upload extends AppCompatActivity {
private static final int PICK_MEDIA_REQUEST = 1;
String MEDIA_url;
String NAME;
String PHONE;
long TIME_ID = System.currentTimeMillis();
String USER_ID;
TextView file;
FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
Button img;
EditText prob;
ProgressBar progressBar;
StorageReference storageReference;
Button upld;
/* access modifiers changed from: private */
public Uri uri;
Button vid;
/* access modifiers changed from: protected */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1 && data != null && data.getData() != null) {
this.uri = data.getData();
this.file.setText(this.uri.getPath());
}
}
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_upload);
this.firebaseAuth = FirebaseAuth.getInstance();
this.firestore = FirebaseFirestore.getInstance();
this.storageReference = FirebaseStorage.getInstance().getReference();
this.prob = (EditText) findViewById(R.id.editTextProblem_upload);
this.file = (TextView) findViewById(R.id.textViewFile_upload);
this.img = (Button) findViewById(R.id.buttonImage_upload);
this.vid = (Button) findViewById(R.id.buttonVideo_Upload);
this.upld = (Button) findViewById(R.id.buttonUpload_upload);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar_upload);
this.progressBar.setVisibility(View.VISIBLE);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
Upload.this.startActivityForResult(intent, 1);
}
});
this.vid.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(intent, 1);
}
});
try {
this.upld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (prob.getText().toString().isEmpty() || file.getText().toString().equals("No file selected")) {
Toast.makeText(getApplicationContext(), "Please write your problem and upload a file!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
upload_file_also(uri);
USER_ID = firebaseAuth.getCurrentUser().getUid();
TIME_ID = System.currentTimeMillis();
firestore.collection("users").document(USER_ID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
NAME = documentSnapshot.getString("NAME_");
PHONE = documentSnapshot.getString("PHONE_");
}
});
NAME = NAME == null ? "null" : NAME;
PHONE = PHONE == null ? "null" : PHONE;
if (!NAME.equals("null") && !PHONE.equals("null")) {
CollectionReference collection = firestore.collection("problems");
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(TIME_ID);
DocumentReference documentReference = collection.document(String.valueOf(sb.toString()));
Map<String, Object> user_problems = new HashMap<>();
user_problems.put("DESCRIPTION_problems", prob.getText().toString());
user_problems.put("NAME_problems", NAME);
user_problems.put("PHONE_problems", PHONE);
user_problems.put("MEDIA_problems", Upload.this.MEDIA_url);
documentReference.set(user_problems).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
Toast.makeText(Upload.this.getApplicationContext(), "Successfully uploaded", Toast.LENGTH_SHORT).show();
Upload.this.startActivity(new Intent(Upload.this.getApplicationContext(), Dash_farmer.class));
Upload.this.finish();
}
});
}
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* access modifiers changed from: private */
public void upload_file_also(Uri fileUri) {
StorageReference storageReference2 = this.storageReference;
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(this.TIME_ID);
final StorageReference sr = storageReference2.child(String.valueOf(sb.toString()));
sr.putFile(fileUri).addOnSuccessListener((OnSuccessListener<TaskSnapshot>) new OnSuccessListener<TaskSnapshot>() {
public void onSuccess(TaskSnapshot taskSnapshot) {
sr.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
Upload.this.MEDIA_url = uri.toString();
Upload.this.progressBar.setVisibility(View.VISIBLE);
Upload.this.upld.setText("TAP AGAIN TO UPLOAD MEDIA");
}
});
}
});
}
}
I'm unable to find why this isn't working. Please put a light on where this is going wrong.
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);
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) {
Link To Data Base structer I recently added a feature in my app where it allows the user to upload a profile picture and that image is stored in firebase and then displayed to the user in the app. The image successfully gets stored in the firebase but when the image is going to be displayed it just removes the default display image and displays nothing.
public class SettingsActivity extends AppCompatActivity {
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
//Android Layout
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private ProgressDialog mProgressDialog;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mStatusBtn = (Button) findViewById(R.id.settings_status_btn);
mImageBtn = (Button) findViewById(R.id.settings_image_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if (!image.equals("default")) {
Picasso.with(SettingsActivity.this).load(image).into(mDisplayImage);
} else {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.goodgolden).into(mDisplayImage);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gallaryIntent = new Intent();
gallaryIntent.setType("image/*");
gallaryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallaryIntent, "Select Image"), GALLERY_PICK);
/*
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
*/
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
String imageUri = data.getDataString();
CropImage.activity(Uri.parse(imageUri))
.setAspectRatio(1, 1)
.start(this);
// Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_SHORT).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("Pleas Stand By");
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 + (".jpeg"));
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
String download_url = task.getResult().getStorage().getDownloadUrl().toString();
// dont know if this solution will work at 6:15 video
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, "Succesful Upload", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error Up Loading", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
07-11 20:15:12.147 30329-30329/com.example.android.lapitchat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.lapitchat, PID: 30329
java.lang.IllegalStateException: Center crop requires calling resize with positive width and height.
at com.squareup.picasso.Request$Builder.build(Request.java:496)
at com.squareup.picasso.RequestCreator.createRequest(RequestCreator.java:758)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:709)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
at com.example.android.lapitchat.SettingsActivity$1.onDataChange(SettingsActivity.java:84)
at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Use latest version of Picasso as -
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load(url).resize(100,100).centerCrop().into(imageView);
Try Replacing the code by this !!!
public class SettingsActivity extends AppCompatActivity {
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private static final int GALLERY_PICK = 1;
// Storage Firebase
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mStatusBtn = (Button) findViewById(R.id.settings_status_btn);
mImageBtn = (Button) findViewById(R.id.settings_image_btn);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mImageStorage = FirebaseStorage.getInstance().getReference();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if(!image.equals("default")) {
//Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.default_avatar).into(mDisplayImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.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 Image...");
mProgressDialog.setMessage("Please wait while we upload and process the image.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filePath = new File(resultUri.getPath());
String current_user_id = mCurrentUser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb_filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").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().getStorage().getDownloadUrl().toString();
UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadUrl = thumb_task.getResult().getStorage().getDownloadUrl().toString();
if(thumb_task.isSuccessful()){
Map update_hashMap = new HashMap();
update_hashMap.put("image", download_url);
update_hashMap.put("thumb_image", thumb_downloadUrl);
mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in uploading thumbnail.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in uploading.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}