Android troubles with Image compression to reduce size - java

I chose an image to be shown on the screen, then I can choose to upload it to firebase. However the images are 2-4mb, and I want to make them smaller without much loss in quality. Is there anyway I can achieve that?. I want to make the images into like 100kb or less before I upload them to firebase.
I have tried with this compressor https://github.com/zetbaitsu/Compressor, but I had troubles making it work.
Here is my full code:
public class AddNewItem extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 177;
private ImageView imageViewAdd;
private EditText titleEditText, descriptionEditText, priceEditText, cityEditText;
private Button lanButton;
private String titleString, descriptionString, priceString, uploadID;
private Button buttonAdd, buttonRotateImage;
private ProgressBar progressBarImage;
private Uri uriSelectedImage;
private String downloadUriImage;
private FirebaseAuth mAuth;
private int imageRotation=0;
private AlertDialog.Builder mbuilder;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef, mDatabaseRefUser;
private StorageTask mUploadTask;
int x = -10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_item);
imageViewAdd = findViewById(R.id.select_image_id);
titleEditText = findViewById(R.id.title_edittext_id);
descriptionEditText = findViewById(R.id.description_edittext_id);
priceEditText = findViewById(R.id.price_edittext_id);
lanButton = findViewById(R.id.lan_button_id);
cityEditText = findViewById(R.id.city_textview_id);
buttonAdd = findViewById(R.id.add_item_button_id);
buttonRotateImage = findViewById(R.id.rotate_image_id);
progressBarImage = findViewById(R.id.progressbar_id);
mAuth = FirebaseAuth.getInstance();
mbuilder = new AlertDialog.Builder(this);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRefUser = FirebaseDatabase.getInstance().getReference("Users");
}
public void selectImage(View view) {
Intent selectImageIntent = new Intent();
selectImageIntent.setType("image/*");
selectImageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(selectImageIntent, "select image to show n upload"), CHOOSE_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriSelectedImage = data.getData();
//new code
Picasso.with(this).load(uriSelectedImage).into(imageViewAdd);
//imageViewAdd.setScaleType(ImageView.ScaleType.FIT_XY); already in xml add_new_item
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
//new code
public void uploadFile(View view) {
// the 1st if statement is to prevent spamming of upload button while upload is in progress
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(this, "is in progress", Toast.LENGTH_SHORT).show();
return;
}
if (titleEditText.getText().toString().isEmpty() || titleEditText.getTextSize() < 5) {
titleEditText.setError("Title is short, minimum 5 characters");
titleEditText.requestFocus();
return;
}
if (descriptionEditText.getText().toString().isEmpty() || descriptionEditText.getTextSize() < 20) {
descriptionEditText.setError("Description is short, minimum 20 characters");
descriptionEditText.requestFocus();
return;
}
if(lanButton.getText().toString().isEmpty()){
lanButton.setError("Please Choose District");
lanButton.requestFocus();
return;
}
if (cityEditText.getText().toString().isEmpty() || cityEditText.length() < 3) {
cityEditText.setError("City/Location is short, minimum 3 characters");
cityEditText.requestFocus();
return;
}
if (priceEditText.getText().toString().isEmpty()) {
priceEditText.setError("Price is needed");
priceEditText.requestFocus();
return;
}
else {
if (uriSelectedImage != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() +
"." + getFileExtension(uriSelectedImage));
mUploadTask = fileReference.putFile(uriSelectedImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Delays the progressbar with 0.5 secs before it shows 0
//user has 0.5 secs to see the 100% bar, code is not necenssary
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBarImage.setProgress(0);
}
}, 500);
Toast.makeText(AddNewItem.this, "Upload succesful", Toast.LENGTH_SHORT).show();
//Upload image is a java class.
uploadID = mDatabaseRef.push().getKey();
UploadImage uploadImage = new UploadImage(titleEditText.getText().toString(),
taskSnapshot.getDownloadUrl().toString(), descriptionEditText.getText().toString(),
cityEditText.getText().toString(), priceEditText.getText().toString(),
imageRotation, lanButton.getText().toString(), mAuth.getCurrentUser().getUid(),
uploadID, mAuth.getCurrentUser().getEmail());
mDatabaseRef.child(uploadID).setValue(uploadImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddNewItem.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());
progressBarImage.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "no file selected", Toast.LENGTH_SHORT).show();
}
}
}
public void rotateImage(View view) {
//set if condition if you want (for example if image has been set or so.... not necessary though.)
imageViewAdd.setRotation(imageViewAdd.getRotation() + 90);
imageRotation = (int) imageViewAdd.getRotation();
//imageViewAdd.setScaleType(ImageView.ScaleType.FIT_XY); already in xml add_new_item
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() == null){
Intent mainActivityIntent = new Intent(this, MainActivity.class);
startActivity(mainActivityIntent);
finish();
}
else {
mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").setValue(true);
}
}
}
I have the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in the manifest.
How can I solve this?
When I used the Compressor, I changed the ACTION_GET_CONTENT to ACTION_PICK, then I added these lines:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriSelectedImage = data.getData();
File imageFile = new File(uriSelectedImage.getPath)
compressedImageBitmap = new Compressor(this).compressToBitmap(imageFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressedImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageByte = baos.toByteArray();
//new code
Picasso.with(this).load(uriSelectedImage).into(imageViewAdd);
//imageViewAdd.setScaleType(ImageView.ScaleType.FIT_XY); already in xml add_new_item
}
}
in the onActivityResult
and declared private Bitmap compressedImageBitmap also private byte[] imageByte;
I then changed the mUploadTask = fileReference.putFile(uriSelectedImage) to putBytes(imageByte). However I receive several errors such as nullpointer on the compressedImageBitmap. Why is that.
How can I solve this issue?

Related

Firebase storage,relatime database android :User does not have permission to access this object

I made a simple app that has a button and an ImageView. When I click on the button, an image (from drawable) gets displayed on the ImageView. I have also written the code for uploading the image on Firebase, but the exception message of onAddFailureListener gives the message User does not have permission to access this object. What should I do?
This answer does not help me.
User does not have permission to access this object . Firebase storage android
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private 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) {
openImagesActivity();
}
});
}
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, 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_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
/*
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
*/
Objects.requireNonNull(taskSnapshot.getMetadata()).getReference().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(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();
}
}
private void openImagesActivity() {
Intent intent = new Intent(this, ImagesActivity.class);
startActivity(intent);
}
}
Realtime Database
{
"rules": {
".read": true,
".write": true
}
}
Storage
rules_version = '2';
service firebase.storage {
match /b/savephoto-a1cc3.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Since I have seen a comment in your code that sounds like this "Allow access by all users", then I recommend you use the following rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
For testing purposes, it will work but I encourage you to change them when you'll launch the application.

Unable to share images in android project chat applicaton

I tried to share the image in my chat application. But was not able to successfully share it. It's selecting the image from the gallery but not appearing in the Userchat screen and not getting upload in the firebase also.
I am not able to find the solution for it. I would very much appreciate if someone can help me out.
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
StorageReference
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
Store that image URL in your chat.
You can do something like this, I am giving you an example for firebase realtime database:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// you should show some progress dialog or progress bar here for better user experience.
progressDialog.show()
fileUri = data.getData();
if (checker.equals("image")) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image files");
final String messgSenderRef = "Messages/" + mAuth.getCurrentUser().getUid() + "/" + userId;
final String messgReceiverRf = "Messages/" + userId + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference messageRef = databaseReference.child("Messages").child(mAuth.getCurrentUser().getUid()).child(userId).push();
final String messagePushId = messageRef.getKey();
final StorageReference filepath = storageReference.child(messagePushId + "." + "jpg");
filepath.putFile(fileUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
// you can show progress of upload here, let suppose you have a progressDialog then:-
double p = ((double) 100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p + "%" + " Uploading....");
}
}).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 filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
// Now you have Uri of your image
downloadUri = task.getResult().toString();
Map<String, Object> messageTextBody = new HashMap<>();
messageTextBody.put("message", downloadUri);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", fileStatus);
messageTextBody.put("from", mAuth.getCurrentUser().getUid());
messageTextBody.put("to", userId);
messageTextBody.put("messageId", messagePushId);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map<String, Object> messageBodydetails = new HashMap<>();
// add message to sender and receiver's
messageBodydetails.put(messgSenderRef + "/" + messagePushId, messageTextBody);
messageBodydetails.put(messgReceiverRf + "/" + messagePushId, messageTextBody);
databaseReference.updateChildren(messageBodydetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
editText.setText("");
}
}
});
} else {
Toast.makeText(ChatActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
} else {
}
}
}
Then in the chat you can check for the changes in the database in realtime and update your chat's recycler view in realtime. Just specify the chat message type to identify and display the view accordingly. If the chat type is text, show the text message. If the chat type is an image, load an image from the URL you have stored.

How do I store downloadUrl of multiple images to the Firebase Firestore ? Unable to create and store inside multiple fields inside Firestore document

Here's what I have been able to get so far. After selecting the images
selectImageButton.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 {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
}
}
});
Inside the OnActivityResult, I am uploading my selected Images to the Firebase Storage and at the same time I want to store my download Urls of those multiple images to the Firebase Firestore
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
final String[] downloadUrl = new String[1];
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
int totalItemsSelected = data.getClipData().getItemCount();
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = storageReference.child("Images").child(fileName);
final int finalI = i;
final int totalCount = totalItemsSelected;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
storeLink(url,totalCount);//Method To Store the Url
}
});
// Toast.makeText(add_for_sale.this, "Uploading works", Toast.LENGTH_SHORT).show();
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
// ImageUploadInfo imageUploadInfo = new ImageUploadInfo(downloadUrl[0],fileName);
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
}
In the method storeLink(url,totalCount), I am creating a map object to create field "imageUrl" inside the document,where "29t0Boxm0fa8UNkomuo5xPLwkx13" is a user id.
private void storeLink(final String url,final int totalCount) {
FirebaseFirestore storeUrl = FirebaseFirestore.getInstance();
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
for (int i=0;i<totalCount;i++) {
final Map<String, Object> image = new HashMap<>();
image.put("imageUrl"+i, url);
DocumentReference documentReference = storeUrl.collection("users").document("29t0Boxm0fa8UNkomuo5xPLwkx13");
documentReference.set(image).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "" +
"OnSuccess : Image Link Saved ");
// startActivity(new Intent(Register.this,LoginActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "OnFailure : " + e.toString());
}
});
}
}
Storage Rules
rules_version = '2'
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Make sure you have made final to Map<String,Object> user = new HashMap<>();
And add user.put("key","value") inside the loop.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final DocumentReference documentReference = db.collection("users").document("multi_image");
final Map<String, Object> user = new HashMap<>();
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
final int totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
final int x = i;
final StorageReference fileToUpload = mStorageRef.child("Images").child("" + x);
fileToUpload.putFile(fileUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> DownloadURL = taskSnapshot.getStorage().getDownloadUrl();
DownloadURL.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
user.put("image_" + x, uri.toString());
Log.v("users", "" + user);
documentReference.update(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v("task", "Success");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v("failed", "" + e);
}
});
}
});
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else if (data.getData() != null) {
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Firebase Storage https://i.stack.imgur.com/HeYvh.png
Firebase Database https://i.stack.imgur.com/3t2aN.png
Here's what worked out for me finally :
Create an ArrayList variable globally
ArrayList<String> imageList;
Then initialize this ArrayList inside the
onActivityResult as imageList = new ArrayList<>(totalItemsSelected); as mentioned inside the code below
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
progressBar.setVisibility(View.VISIBLE);
final int totalItemsSelected = data.getClipData().getItemCount();
count = totalItemsSelected;
imageList = new ArrayList<>(totalItemsSelected);
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = ImageFolder.child(fileName);
final int finalI = i;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.INVISIBLE);
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
imageList.add(url);
// Toast.makeText(add_for_sale.this, imageList.get(finalI), Toast.LENGTH_SHORT).show();
Log.i(TAG,"Added To List");
}
});
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Select Two or More Images", Toast.LENGTH_SHORT).show();
}
}
}
Now to Save the Url Links to the Firebase Firestore Add the links to the ArrayList as imageList.add(url;)
and upload this list imageList to the FireStore as
Map<String,Object> imageUrl = new HashMap<>();
imageUrl.put("ImageUrl", imageList);
String userId;
userId = firebaseUser.getUid();
firebaseFirestore.collection("ImageDetails").document(userId)
.set(imageUrl,SetOptions.merge());
This will create an array of ImageUrl inside your firestore document

image taken from gallery is unable to set in image view

I am taking image from camera as well as from gallery,after getting the image, I want to show the image in imageview.
Image that is captured by camera successfully is shown in imageview but when I want to select it from gallery it does not show the image and it also does not show any error. It was working properly but later I add camera feature in activity, it's not working well.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
} catch(FileNotFoundException ex) {
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v) {
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty()) {
subject.setError("subject is required");
} else if(det.isEmpty()) {
detail.setError("subject is required");
} else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
} else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
only change onActivityResult method remove else if block form id condition like below code...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
selectedImage = BitmapFactory.decodeStream(imageStream);
You should check if selectedImage -the bitmap- is null.
I bet selectedImage==null.
This happens if the bitmap would become too big for available memory.
You should scale it down while loading from stream.
Remember: from the camera you only obtain a thumbnail. Thats the difference.
Here's my code to set a rounding photo from gallery or camera into ImageButton and it works perfectly :
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
In your code, try to add createScaledBitmap to resize your photo like this:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}

Class variable not changing in IF or Switch statements

Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.

Categories

Resources