The app is allowing me to capture pictures, then allowing me to accept or reject pictures, showing me accepted images inside the app but not saving them to the device. All help much appreciated?
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Demo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("Demo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
}
Check if you have the right storage permissions.
I suggest you to move the image and then rename it;
Related
I combined the two Java codes, but I have a problem: when I take a picture and then I want to read the text with this picture, it writes the text of the program-assigned image (not taken photo).
The problem is the combination of commands, which I can not sort. Always read the original image (ImageView is installed with a Bitmap test image).
I tried many times but could not order.
P.S I do not want to save the captured image.
Thanks in advance for the feedback.
my Java code:
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888; ///////
private ImageView imageView;///
private static final int MY_CAMERA_PERMISSION_CODE = 100;////
////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}/////////////
ImageView imageview;
Button btnProcess;
EditText txtView, txtVieww;
Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.image_view);////
Button photoButton = (Button) this.findViewById(R.id.button1);////
imageview = findViewById(R.id.image_view);
btnProcess = findViewById(R.id.btnProcess);
txtView = findViewById(R.id.txtView);
txtVieww = findViewById(R.id.txtVieww);
photo = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.newyt);
imageview.setImageBitmap(photo);
/////
photoButton.setOnClickListener(v -> {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
///////
btnProcess.setOnClickListener(v -> {
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
txtView.setText(R.string.error_prompt);
txtVieww.setText(R.string.error_prompt);
} else {
Frame frame = new Frame.Builder().setBitmap(photo).build();
SparseArray<TextBlock> items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append("/");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
final String substringi = strBuilder.substring(0, 10).replaceAll("\\s+", "");
final String substringg = substringi.substring(0, 5);
txtView.setText(substringi);
txtVieww.setText(substringg);
}
});
}
}
I have added Camera permissions as well which is working perfectly but the image view is not holding the image that is captured. The manifest file is also proper still. The app isn't crashing even it is not showing any errors as well. And I even want to add the image to the database.
public class RiderProfile extends AppCompatActivity {
ImageView imgDp,imgDlFront,imgDlback;
TextView txtDp,txtDl;
Button btnSave;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "1111";
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider_profile);
imgDp = (ImageView)findViewById(R.id.imgDp);
imgDlFront = (ImageView)findViewById(R.id.imgDlFront);
imgDlback = (ImageView)findViewById(R.id.imgDlback);
txtDp = (TextView) findViewById(R.id.txtDp);
txtDl = (TextView)findViewById(R.id.txtDl);
btnSave = (Button) findViewById(R.id.btnSave);
imgDp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo1 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDp.setImageBitmap(photo1);
}
}
});
imgDlFront.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo2 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlFront.setImageBitmap(photo2);
}
}
});
imgDlback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo3 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlback.setImageBitmap(photo3);
}
}
});
}
}
1. #Override
public void onCameraOpen() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
try {
imageFile = CameraUtils.createImageFile(this);
} catch (IOException e) {
e.printStackTrace();
return;
}
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imageFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(pictureIntent, IntentRequestCode.RESULT_CODE_IMAGE_CAPTURE);
}
}
2. #Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_CODE_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
onCaptureImage(imageFile, imageUri);
} else {
Toast.makeText(this, "Camera canceled", Toast.LENGTH_SHORT).show();
}
break;
}
}
3. void onCaptureImage(File imageFile, Uri imageUri) {
Uri uri = Uri.fromFile(imageFile);
String selectedImagePath = CameraUtils.getPath(application, uri);
File file1 = new File(selectedImagePath);
if (file1.length() != 0) {
FileAttachments b_data = new FileAttachments();
b_data.setFileName(file1.getName());
CameraUtils.writeScaledDownImage(file1, getApplication());
b_data.setFile(file1);
}
}
There is camera codes in my project that another developer who wrote. It takes photo by the device camera but it doesn't save photo in a file of device. It must to save the photo in a file of mobile device. I post here java class and other codes that is related with camera. How can save the photo in device?
SendMessagePage.java
public class SendMessagePage extends BaseActivity {
private static final int CAMERA_RQ = 6969;
private static final int PERMISSION_RQ = 84;
File saveDir = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
}
final MaterialCamera materialCamera =
new MaterialCamera(this)
.saveDir(saveDir)
.showPortraitWarning(true)
.allowRetry(true)
.defaultToFrontFacing(true)
.allowRetry(true)
.autoSubmit(false)
.labelConfirm(R.string.mcam_use_video);
LinearLayout takePhoto = (LinearLayout) findViewById(R.id.take_photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
if (1 == 2) {
}
ActivityCompat.requestPermissions(SendMessagePage.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 23
);
}
}
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
materialCamera
.stillShot() // launches the Camera in stillshot mode
.labelConfirm(R.string.mcam_use_stillshot);
materialCamera.start(CAMERA_RQ);
}
});
}
private String readableFileSize(long size) {
if (size <= 0) return size + " B";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups))
+ " "
+ units[digitGroups];
}
private String fileSize(File file) {
return readableFileSize(file.length());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Received recording or error from MaterialCamera
if (requestCode == CAMERA_RQ) {
if (resultCode == RESULT_OK) {
final File file = new File(data.getData().getPath());
Toast.makeText(
this,
String.format("Saved to: %s, size: %s", file.getAbsolutePath(), fileSize(file)),
Toast.LENGTH_LONG)
.show();
} else if (data != null) {
Exception e = (Exception) data.getSerializableExtra(MaterialCamera.ERROR_EXTRA);
if (e != null) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(
this,
"Videos will be saved in a cache directory instead of an external storage directory since permission was denied.",
Toast.LENGTH_LONG)
.show();
}
}
Define this in your class
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
Uri picUri;
File imagefile;
Use the below code for capturing picture. The picture is saved in DCIM folder
takePicture.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureName = getPictureName();
imagefile = new File(pictureDirectory, pictureName);
picUri = Uri.fromFile(imagefile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
imageView.setImageURI(picUri);
}
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
nameOfFile=timestamp + ".jpg";
return timestamp + ".jpg";
}
NOTE: This code is working and has no errors as i have used this code in one of my projects. It has been extracted from code of mine.
I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:
//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
});
//Handling the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
beginCropProfile(data.getData());
}else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
beginCropCover(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(requestCode, resultCode, data);
}
}
private void beginCropProfile(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
private void beginCropCover(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
private void handleCrop(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
regCoverPhoto.setImageURI(Crop.getOutput(result));
mCoverPhotoUri = Crop.getOutput(result);
uploadCoverToStorage();
Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
}else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
regUserProfile.setImageURI(Crop.getOutput(result));
mProfilePhotoUri = Crop.getOutput(result);
uploadProfileToStorage();
Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
} else if (resultCode == Crop.RESULT_ERROR) {
Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
}
}
I haven't used this library particularly, but custom request codes seem to be the problem.
Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.
See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494
List item
Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them
Also i'm using these library inside gradel
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'
And inside Mainfrest i have specifed this as <activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait" />
side2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_side_2";
image_number_5 = "image_side_2";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_back";
image_number_6 = "image_back";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
if (image_name.equals("image_front")) {
image.setImageURI(result.getUri());
} else if (image_name.equals("image_top")) {
topImage.setImageURI(result.getUri());
} else if (image_name.equals("image_bottom")) {
bottomImage.setImageURI(result.getUri());
} else if (image_name.equals("image_side_1")) {
side1Image.setImageURI(result.getUri());
} else if (image_name.equals("image_side_2")) {
side2Image.setImageURI(result.getUri());
} else if (image_name.equals("image_back")) {
backImage.setImageURI(result.getUri());
}
cropped = result.getUri();
File path = getExternalCacheDir();
new File(String.valueOf(path)).mkdir();
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name22 = dateFormat.format(new Date());
// String helloWorld = cropped.toString();
// String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/"));
// String name="snehal_go";
savedFileDestination = new File(imagePath, name22 + ".jpg");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);
String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
Random generator = new Random();
randomStringBuilder = new StringBuilder();
int randomLength = 10;
for (int i = 0; i < randomLength; i++) {
randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
}
// Create imageDir
mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");
FileOutputStream fos = null;
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.i("File", mypath.toString());
if (image_name.equals("image_front")) {
uploadImage_front();
} else if (image_name.equals("image_top")) {
uploadImage_top();
} else if (image_name.equals("image_bottom")) {
uploadImage_bottom();
} else if (image_name.equals("image_side_1")) {
uploadImage_side1();
} else if (image_name.equals("image_side_2")) {
uploadImage_side2();
} else if (image_name.equals("image_back")) {
uploadImage_back();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(false)
.setMinCropWindowSize(600, 600)
.setAspectRatio(2, 2)
.setRequestedSize(500, 500)
.start(this);
}
Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"
I'm not good in english...
// took extra int
static int a=0;
private void onClickData() {
cover_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=1;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
author_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=2;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
a=0;
}
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
a=0;
}
}
I'm open gallery from one of my fragment but after i select image from gallery
the image doesn't show to me in view.
in the onActivityResult I have error in the rootview in this line:
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
and I test with toast to show me the selected image path but
it doesnt show me the path.
here is my fragment code:
public class Share_Page extends Fragment implements View.OnClickListener {
private static final int RESULT_OK = 1;
String path="";
String imgPath, fileName;
private Button home_page,search_page;
private static int RESULT_LOAD_IMG = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.share, container, false);
home_page = (Button) rootview.findViewById(R.id.home_page);
search_page = (Button) rootview.findViewById(R.id.search_page);
rootview.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery();
}
});
btn_click();
return rootview;
}
public void loadImagefromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
//ImageView imgView = (ImageView) findViewById(R.id.imgView);
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
path=imgPath;
} else {
Toast.makeText(getActivity(), "image not select",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(getActivity(), "error`enter code here`...!", Toast.LENGTH_LONG)
.show();
}
}
This method is for intent to open gallery and pick image:
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityIfNeeded(galleryIntent, RESULT_LOAD_IMG);
}
And here is result after a image picked. As u see i use image to change a background, u can put it into imageView or what ever u wanted
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
Drawable d = new BitmapDrawable(getResources(), imgDecodableString);
relativeLayout.setBackground(d);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Also please remember to add a permissions in Manifest
Example how to use a permissions runtime, paste it into Activity
private static final int REQUEST_CODE_EXTERNAL_STORAGE = 1;
private static final int REQUEST_CODE_CAMERA = 2;
private static int RESULT_LOAD_IMG = 1;
#TargetApi(23)
public void checkCameraPermission(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return;
}
if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to save image",
LENGTH_SHORT).show();
}
break;
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to start SOS",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
And if u want to check permissions on fragment u should do like this:
((Activity) getContext()).checkAnyPermission();
u should check this after u open a gallery