I am using ArthurHub's library to crop a image and put it in a ImageButton or ImageView.
Crop Activity starts smoothly but after cropping when I clicks to CROP button, my app reruns and opens MainActivity.
It seems to me that there is no error in the code and also I have checked it 5-6 times.
Thanks!!!
Here is my code...
public class AddActivity extends AppCompatActivity {
private ImageButton add_image_button;
private Uri imageUri;
private String imageUrl;
private String recordPermission = Manifest.permission.RECORD_AUDIO;
private String readExternalStorage = Manifest.permission.READ_EXTERNAL_STORAGE;
private String recordFile;
private int PERMISSION_CODE = 7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
add_image_button = findViewById(R.id.add_image_button);
CropImage.activity(imageUri).start(AddActivity.this);
add_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkReadExternalStoragePermissions();
CropImage.activity(imageUri).start(AddActivity.this);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
add_audio_button.setImageURI(imageUri);
}else {
Toast.makeText(this, "Try again...", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddActivity.this, MainActivity.class));
finish();
}
}
private boolean checkRecordPermissions() {
if (ActivityCompat.checkSelfPermission(this, recordPermission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{recordPermission}, PERMISSION_CODE);
return false;
}
}
private boolean checkReadExternalStoragePermissions() {
if (ActivityCompat.checkSelfPermission(this, readExternalStorage) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{readExternalStorage}, PERMISSION_CODE);
return false;
}
}
}
implementation 'com.github.Drjacky:ImagePicker:1.8.4'
use this library it is one of best for imagePicker
it will be give functionality like
1)crop
2)zoom
3)rotate
I have found out the error, there was a slight mistake in the code.
I used add_audio_button.setImageUri(imageUri) instead of add_image_button.setImageUri(imageUri); here:
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
add_audio_button.setImageURI(imageUri);
Related
How can I check permission for every activity ???
I am trying to make a video player app. I am trying to get External Storage on Android 11 and the lower version. When I am clicking on the button it is asking for permission for both android 11 and the lower version (ex: Kitkat). But the problem is when I am going to the next activity after granting permission and turning off the storage permission from settings in the background. It was not asking for any permission for this new activity.
If anyone has any solution please help me I was shared my code bellow
My permission activity(MainActivity.java) and I want to check permission in (activity_allow_access.java).
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 100;
final static int REQUEST_CODE = 333;
private Button signIn;
public static String PREFS_NAME="MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = findViewById(R.id.button);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
});
}
private void requestPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package",this.getPackageName(),null);
intent.setData(uri);
storageActivityResultLauncher.launch(intent);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
storageActivityResultLauncher.launch(intent);
}
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
}
}
private ActivityResultLauncher<Intent> storageActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
if(Environment.isExternalStorageManager()){
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
else{
Toast.makeText(MainActivity.this, "storage permission required", Toast.LENGTH_SHORT).show();
}
}
}
}
);
public boolean checkPermission(){
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}else {
int write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED;
}
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
#SuppressLint("MissingSuperCall")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.length >0){
boolean write = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean read = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(write && read) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
} else {
requestPermission();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if (checkPermission()) {
startActivity(new Intent(MainActivity.this,AllowAccessActivity.class));
finish();
}
}
}
AllowAccessActivity.java
public class AllowAccessActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allow_access);
}
}
Visitor Details
I have a dialog in Visitor Activity. When I click on the icon, it will redirect to Camera Activity. Then when click Confirm button in Camera Activity, it will send the intent back to previous Activity which is Visitor Activity. The problem is how should I pass the intent result from Camera Activity back to the dialog in Visitor Activity. The intent data should be placed in the Pass No Edit Text. I'm using material dialog without any Fragment that attached to that dialog. It all placed in Visitor Activity. Can someone please help me? Thank you!
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
}
}
First you need to take the view object globally out of that checkIn methoed
View view;
view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
Now under your onActivityResult method, as i can see you already getting the barcode there, so just initiate the EditText object again on that same simply set the data in it.
barCode = data.getStringExtra("barCode");
EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
etPassNo.setText(barCode);
Let me know if that works.
you can do it using interface
public interface OnBarcodeSelect{
void onBarcodeSelected(String barcode);}
OnBarcodeSelect onBarcodeSelect;
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
onBarcodeSelect = new OnBarcodeSelect() {
#Override
public void onBarcodeSelected(String barcode) {
//handle barcode here
etPassNo.setText(barcode);
}
}
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
if(onBarcodeSelect != null){
onBarcodeSelect.onBarcodeSelected(barCode);
}
}
}
I am unable to upload two separate image in Two Imageview using onActivityResult.
Here when I Select ImageView one and Cope Image then image is set in Imageview.
But when I select Imageview Two and it opens Gallery and When I crop image and press Ok then Imageview one gets replaced it's previous image instead that Imageview two should have the selected image and Imageview one should have same image previously selected
My Activity is
import java.util.Random;
public class UploadBook extends AppCompatActivity {
ImageView iv1,iv2;
private static final int CAMERA_REQUEST_CODE_two=2;
private static final int RESULT_CODE_TWO=2;
private static final int CROP_IMAGE_ACTIVITY_REQUEST_CODE_TWO=2;
private static final int CAMERA_REQUEST_CODE = 1;
Uri filePath = null;
Uri imagePath = null;
public Books b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_book_request);
iv1 = (ImageView) findViewById(R.id.itemImage1);
iv2 = (ImageView) findViewById(R.id.itemImage2);
imageoneButtonclick();
imagetwoButtonclick();
void imageoneButtonclick() {
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(filePath).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(UploadBook.this);
}
});
}
void imagetwoButtonclick() {
iv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(imagePath).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(UploadBook.this);
}
});
}
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 == CAMERA_REQUEST_CODE_two && resultCode == RESULT_CODE_TWO) {
imagePath = data.getData();
iv2.setImageURI( imagePath);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultoneUri = result.getUri();
iv1.setImageURI(resultoneUri);
filePath = resultoneUri;
}
if (resultCode == RESULT_CODE_TWO) {
Uri resultUri = result.getUri();
iv2.setImageURI(resultUri);
imagePath = resultUri;
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
Please Help
Thanks in advance.
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?
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());
}