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();
}
}
}
}
Related
I cannot upload the profile image on firebase storage.
I'm getting printed the error from the toast.
Why is this happening? I cannot figure the problem out, I reviewed my code so many times.
What could the problem be and how can I adjust my code in order to make this work?
Thank you in advance to everyone.
public class ProfiloUtenteActivity extends AppCompatActivity {
private ImageView mImageBtn;
private ImageView mSettingsBtn, mPersonalReviewsBtn, mShowFriendsBtn;
private CircleImageView mProfileImage;
private TextView mMailAcc, mUsernameAcc;
private static final int GALLERY_PICK = 1;
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private ProgressDialog mProgress;
private StorageReference mImageStorage;
private String myUri = "";
private Uri imageUri;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profilo_utente);
mShowFriendsBtn = findViewById(R.id.imageShowFriends);
mPersonalReviewsBtn = findViewById(R.id.imagePersonalReviews);
mSettingsBtn = (ImageView) findViewById(R.id.imageViewSettings);
mImageBtn = (ImageView) findViewById(R.id.change_image_btn);
mProfileImage = (CircleImageView) findViewById(R.id.profile_image);
mMailAcc = (TextView) findViewById(R.id.textViewMailAcc);
mUsernameAcc = (TextView) findViewById(R.id.textView7);
auth = FirebaseAuth.getInstance();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("utenti").child(current_uid);
mImageStorage = FirebaseStorage.getInstance().getReference();
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Seleziona una foto"), GALLERY_PICK);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
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);
Uri resultUri = result.getUri();
StorageReference filepath = mImageStorage.child("profile_images").child("1wq");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(ProfiloUtenteActivity.this, "Funziona", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ProfiloUtenteActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
When a Task fails, it contains an exception that has more information about the failure. Logging that allows you to find out the cause of the problem:
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(ProfiloUtenteActivity.this, "Funziona", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ProfiloUtenteActivity.this, "Error", Toast.LENGTH_SHORT).show();
Log.e("Upload", "Upload failed", task.getException());
}
}
Once you get the error message, I recommend searching for it was likely somebody has dealt with it before.
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();
}
}
}
}
Error show in image.Please Click here for view Image
When User Want to change his profile picture.and upload new image . Firebase get uri of new image ad replaced with old uri value. That work is done with .setValue(). Now i am unbale to use that method. Please Any one tell me Solution, how i cando it easily.
enter code here
` package junaidandusman.newchatapp;
public class SettingActivity extends AppCompatActivity {
private CircleImageView SettingDisplayprofileImage;
private TextView SettingDisplayName;
private TextView SettingDisplayStatus;
private Button SettingChangeprofileImage;
private Button SettingChangeStatus;
private DatabaseReference Reference;
private FirebaseAuth mAuth;
private final static int Gallery_Pick=1;
private StorageReference Storagereference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
SettingDisplayprofileImage=(CircleImageView)
findViewById(R.id.setting_profile_image);
SettingDisplayName=(TextView)
findViewById(R.id.setting_username);
SettingDisplayStatus=(TextView)
findViewById(R.id.setting_userstatus);
SettingChangeprofileImage=(Button)
findViewById(R.id.setting_change_profile_image);
SettingChangeStatus=(Button)
findViewById(R.id.setting_change_profile_status);
Storagereference=FirebaseStorage.getInstance().getReference().child("profile_images");
mAuth=FirebaseAuth.getInstance();
String online_user_id=mAuth.getCurrentUser().getUid();
Reference=FirebaseDatabase.getInstance().getReference().child("users").child(online_user_id);
Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("user_name").getValue().toString();
String status=dataSnapshot.child("user_status").getValue().toString();
String image=dataSnapshot.child("user_image").getValue().toString();
String thumb_image=dataSnapshot.child("user_thumb_image").getValue().toString();
SettingDisplayName.setText(name);
SettingDisplayStatus.setText(status);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
SettingChangeprofileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery_intent=new Intent();
gallery_intent.setAction(Intent.ACTION_GET_CONTENT);
gallery_intent.setType("image/*");
startActivityForResult(gallery_intent,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){
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();
String user_id=mAuth.getCurrentUser().getUid();
StorageReference FilePath=Storagereference.child(user_id+".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this,"Saving your profile image to Firebase Storag",Toast.LENGTH_LONG).show();;
String downloadurl=task.getResult().getStorage().getDownloadUrl().toString();
Storagereference.child("user_image").setValue(downloadurl);
}
else
{
Toast.makeText(SettingActivity.this,"Error occured,while uploading your profile image",Toast.LENGTH_SHORT).show();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
How I can store downloaduri value to Storagereference using .setValue or any other method that can do this?
I'm trying to show the image which has been sucessfully uploaded in firebase storage and whose unique id is also updated in Firebase Database under "pics" in my Imageview but I did tried multiple time but am unable to show the image or retrive images .
Below is my Firebase Database Structure.
and my Imageview is
Where image should be displayed in place of Bookshelf which is default pic but unable to do so.
Below is my upload Activity
public class UploadBook extends AppCompatActivity {
FirebaseDatabase database;
EditText etAuthor, etbookDesc, etbookTitle, etName, etEmail, etMobile, etUniversity, etbookPrice;
ImageView iv1;
Button b1;
AlertDialog.Builder builder1;
DatabaseReference dbreference;
String item = "start"; // for spinner
FirebaseStorage storage;
private static final int CAMERA_REQUEST_CODE = 1;
StorageReference mStorageRef;
FirebaseAuth fauth;
int count = 0;
Uri filePath = null;
public Books b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.nepalpolice.bookbazaar.R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload book");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
ActivityCompat.requestPermissions(UploadBook.this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference();
fauth = FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
iv1 = (ImageView) findViewById(com.nepalpolice.bookbazaar.R.id.itemImage1);
etAuthor = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText1);
etbookDesc = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText2);
etbookTitle = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText3);
etName = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText4);
etEmail = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText5);
etMobile = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText6);
etUniversity = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText7);
etbookPrice = (EditText) findViewById(com.nepalpolice.bookbazaar.R.id.editText8);
b1 = (Button) findViewById(com.nepalpolice.bookbazaar.R.id.buttonPost);
t3 t = new t3();
t.execute();
Spinner spinner = (Spinner) findViewById(com.nepalpolice.bookbazaar.R.id.spinner1);
final String[] items = new String[]{"Select your category :", "Computer Science", "Electronics", "Mechanical", "Civil", "Electrical", "Mechatronics", "Software", "Others"};
ArrayAdapter<String> spinneradapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
spinner.setAdapter(spinneradapter);
spinner.setActivated(false);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
item = adapterView.getItemAtPosition(position).toString();
count = position;
if (position == 0)
return;
Toast.makeText(adapterView.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
imageButtonclick();
postButtonClick();
builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Discard this item !");
builder1.setCancelable(true);
builder1.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
dialog.cancel();
}
});
}
void imageButtonclick() {
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(filePath).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(UploadBook.this);
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);
//startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
void postButtonClick() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (count == 0) {
Toast.makeText(UploadBook.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
return;
}
if (!TextUtils.isDigitsOnly(etMobile.getText()) || etMobile.getText().toString().trim().length() != 10) {
Toast.makeText(UploadBook.this, "Please check number format !", Toast.LENGTH_SHORT).show();
return;
}
if (etAuthor.getText().toString().trim().length() > 0 && etbookDesc.getText().toString().trim().length() > 0
&& etbookTitle.getText().toString().trim().length() > 0 && etName.getText().toString().trim().length() > 0
&& etEmail.getText().toString().trim().length() > 0 && etMobile.getText().toString().trim().length() > 0
&& etUniversity.getText().toString().trim().length() > 0 && etbookPrice.getText().toString().trim().length() > 0
&& filePath!=null) {
String bauthor = etAuthor.getText().toString();
String bdesc = etbookDesc.getText().toString();
String btitle = etbookTitle.getText().toString();
String sellername = etName.getText().toString();
String selleremail = etEmail.getText().toString();
Long sellermobile = Long.parseLong(etMobile.getText().toString());
String selleruniversity = etUniversity.getText().toString();
Double bprice = Double.parseDouble(etbookPrice.getText().toString());
Toast.makeText(getApplicationContext(), "Your book will be uploaded shortly !", Toast.LENGTH_SHORT).show();
b = new Books(btitle, bauthor, bdesc, sellername, selleremail, sellermobile, item, selleruniversity, bprice);
String bookid = dbreference.child("books").child(item).push().getKey();
dbreference.child("books").child(item).child(bookid).setValue(b);
t2 t2 = new t2();
t2.execute(bookid);
Intent in = new Intent(UploadBook.this, BooksPage.class);
startActivity(in);
finish();
} else {
Toast.makeText(UploadBook.this, "Please enter your complete details !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
/*AlertDialog alert2 = builder1.create();
alert2.show();*/
CustomDialogClass cdd = new CustomDialogClass(UploadBook.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
filePath = data.getData();
iv1.setImageURI(filePath);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
iv1.setImageURI(resultUri);
filePath = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
class t2 extends AsyncTask<String,Integer,Boolean> {
#Override
protected Boolean doInBackground(final String... bookid) {
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadBook.this, "Upload Failed : " + e, Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
}
class t3 extends AsyncTask<String,Integer,Boolean>{
#Override
protected Boolean doInBackground(String... strings) {
publishProgress();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
etName.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("name","Delault name"));
etEmail.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("email","Default email"));
etUniversity.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("university","Default university"));
etMobile.setText(String.valueOf(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("phone","Default phone")));
}
}
and my Adapter class is
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books b;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
ImageView iv;
MyViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.my_card_view);
iv = (ImageView) itemView.findViewById(R.id.imageView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
bookName = (TextView) itemView.findViewById(R.id.bookName);
bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
bookCall = (TextView) itemView.findViewById(R.id.bookCall);
fauth = FirebaseAuth.getInstance();
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
b = bookslist.get(position);
holder.bookName.setText(b.getBname());
holder.bookAuthor.setText(b.getBauthor());
holder.bookDesc.setText(b.getBdesc());
holder.bookPrice.setText("Rs. "+b.getPrice());
holder.bookCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.e("Current user is ", fauth.getCurrentUser().getEmail());
b = bookslist.get(position);
String[] arr = {b.getSelleremail(),b.getSellername(),b.getBname(),b.getBauthor()};
//Log.e("Seller is ",b.getSellername());
Intent in = new Intent(v.getContext(),Chat.class);
in.putExtra("seller",arr);
v.getContext().startActivity(in);
}
});
Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);
}
#Override
public int getItemCount() {
return bookslist.size();
}
}
Please help.
Here is my whole project
https://github.com/BlueYeti1881/Pustak
Thanks in advance.
In UploadBook class change this
if(filePath != null) {
mStorageRef.child(bookid[0]).putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Toast.makeText(UploadBook.this, "Upload successful", Toast.LENGTH_SHORT).show();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
To This-
final StorageReference ref = mStorageRef.child(bookid[0]);
UploadTask uploadTask = ref.putFile(file);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
dbreference.child("books").child(item).child(bookid[0]).child("pics").setValue(downloadUri.toString());
} else {
// Handle failures
}
}
});
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
}
}
});
}
});
}