Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AC-788 Added crop image feature at registration screen #768

Merged
merged 4 commits into from
Jun 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions openmrs-client/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ dependencies {
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0'
//google place api
implementation 'com.google.android.libraries.places:places:2.1.0'
//Image Cropping Library
implementation 'com.github.yalantis:ucrop:2.2.5'
}

play {
Expand Down
4 changes: 4 additions & 0 deletions openmrs-client/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@
android:theme="@style/AppThemeOrig"
android:label="@string/contact_us"/>

<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:theme="@style/AppTheme"/>

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${GOOGLE_PLACE_API_KEY}"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
Expand All @@ -29,7 +30,6 @@
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.Editable;
Expand Down Expand Up @@ -58,6 +58,7 @@
import androidx.annotation.NonNull;
import androidx.annotation.StringDef;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.common.api.ApiException;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
Expand All @@ -69,6 +70,7 @@
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import com.hbb20.CountryCodePicker;
import com.yalantis.ucrop.UCrop;

import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTime;
Expand Down Expand Up @@ -96,7 +98,6 @@

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.text.SimpleDateFormat;
Expand All @@ -120,13 +121,11 @@ public class AddEditPatientFragment extends ACBaseFragment<AddEditPatientContrac
private RelativeLayout relativeLayout;
rishabh-997 marked this conversation as resolved.
Show resolved Hide resolved
private LocalDate birthdate;
private DateTime bdt;

private LinearLayout linearLayoutName;
private RelativeLayout relativeLayoutDOB;
private LinearLayout linearLayoutContactInfo;
private CheckBox unidentifiedCheckBox;
private Boolean isPatientUnidentified = false;

private TextInputLayout firstNameTIL;
private TextInputLayout middleNameTIL;
private TextInputLayout lastNameTIL;
Expand Down Expand Up @@ -160,17 +159,12 @@ public class AddEditPatientFragment extends ACBaseFragment<AddEditPatientContrac
private Bitmap patientPhoto = null;
private String patientName;
private File output = null;
private final static int IMAGE_REQUEST = 1;
private final static int GALLERY_IMAGE_REQUEST = 2;
private OpenMRSLogger logger = new OpenMRSLogger();
private boolean isUpdatePatient = false;
private Patient updatedPatient;

@Retention(SOURCE)
@StringDef({StringValue.MALE, StringValue.FEMALE})
public @interface StringValue {
String FEMALE = "F";
String MALE = "M";
public static AddEditPatientFragment newInstance() {
return new AddEditPatientFragment();
}

@Override
Expand Down Expand Up @@ -212,10 +206,10 @@ public void setErrorsVisibility(boolean givenNameError,

dateTimeFormatter = DateTimeFormat.forPattern(DateUtils.DEFAULT_DATE_FORMAT);
String minimumDate = DateTime.now().minusYears(
ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE)
.toString(dateTimeFormatter);
ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE)
.toString(dateTimeFormatter);
String maximumDate = DateTime.now().toString(dateTimeFormatter);
if(unidentifiedCheckBox.isChecked()) {
if (unidentifiedCheckBox.isChecked()) {
dobError.setText(getString(R.string.dob_error_for_unidentified));
} else {
dobError.setText(getString(R.string.dob_error, minimumDate, maximumDate));
Expand Down Expand Up @@ -362,7 +356,7 @@ private Patient updatePatientWithData(Patient patient) {
String unvalidatedDate = edDob.getText().toString().trim();

DateTime minDateOfBirth = DateTime.now().minusYears(
ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE);
ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE);
DateTime maxDateOfBirth = DateTime.now();

if (DateUtils.validateDate(unvalidatedDate, minDateOfBirth, maxDateOfBirth)) {
Expand All @@ -383,9 +377,9 @@ private Patient updatePatientWithData(Patient patient) {
} else {
patient.setGender(null);
}

// Add patient photo
if (patientPhoto != null){
if (patientPhoto != null) {
patient.setPhoto(patientPhoto);
}

Expand Down Expand Up @@ -447,20 +441,16 @@ public void showUpgradeRegistrationModuleInfo() {
@Override
public boolean areFieldsNotEmpty() {
return (!ViewUtils.isEmpty(edfName) ||
(!ViewUtils.isEmpty(edmName)) ||
(!ViewUtils.isEmpty(edlName)) ||
(!ViewUtils.isEmpty(edDob)) ||
(!ViewUtils.isEmpty(edYear)) ||
(!ViewUtils.isEmpty(edAddr1)) ||
(!ViewUtils.isEmpty(edAddr2)) ||
(!ViewUtils.isEmpty(edCity)) ||
(!ViewUtils.isEmpty(edState)) ||
(!ViewUtils.isCountryCodePickerEmpty(mCountryCodePicker)) ||
(!ViewUtils.isEmpty(edPostal)));
}

public static AddEditPatientFragment newInstance() {
return new AddEditPatientFragment();
(!ViewUtils.isEmpty(edmName)) ||
(!ViewUtils.isEmpty(edlName)) ||
(!ViewUtils.isEmpty(edDob)) ||
(!ViewUtils.isEmpty(edYear)) ||
(!ViewUtils.isEmpty(edAddr1)) ||
(!ViewUtils.isEmpty(edAddr2)) ||
(!ViewUtils.isEmpty(edCity)) ||
(!ViewUtils.isEmpty(edState)) ||
(!ViewUtils.isCountryCodePickerEmpty(mCountryCodePicker)) ||
(!ViewUtils.isEmpty(edPostal)));
}

private void resolveViews(View v) {
Expand Down Expand Up @@ -524,7 +514,7 @@ private void fillFields(final Patient patient) {
if (StringUtils.notNull(patient.getBirthdate()) || StringUtils.notEmpty(patient.getBirthdate())) {
bdt = DateUtils.convertTimeString(patient.getBirthdate());
edDob.setText(DateUtils.convertTime(DateUtils.convertTime(bdt.toString(), DateUtils.OPEN_MRS_REQUEST_FORMAT),
DateUtils.DEFAULT_DATE_FORMAT));
DateUtils.DEFAULT_DATE_FORMAT));
}

if ((StringValue.MALE).equals(patient.getGender())) {
Expand Down Expand Up @@ -559,7 +549,7 @@ private void addSuggestionsToCities() {
if (resourceId != 0) {
String[] states = getContext().getResources().getStringArray(resourceId);
ArrayAdapter<String> state_adapter = new ArrayAdapter<>(getContext(),
android.R.layout.simple_dropdown_item_1line, states);
android.R.layout.simple_dropdown_item_1line, states);
edState.setAdapter(state_adapter);
}
}
Expand Down Expand Up @@ -627,11 +617,11 @@ public void afterTextChanged(Editable s) {

capturePhotoBtn.setOnClickListener(view -> {
boolean showRemoveButton = true;
if(patientPhoto == null)
if (patientPhoto == null)
showRemoveButton = false;
CameraOrGalleryPickerDialog cameraOrGalleryPickerDialog = new CameraOrGalleryPickerDialog(showRemoveButton);
cameraOrGalleryPickerDialog.setTargetFragment(AddEditPatientFragment.this,1000);
cameraOrGalleryPickerDialog.show(getFragmentManager(),"tag");
cameraOrGalleryPickerDialog.setTargetFragment(AddEditPatientFragment.this, 1000);
cameraOrGalleryPickerDialog.show(getFragmentManager(), "tag");
});

patientImageView.setOnClickListener(view -> {
Expand Down Expand Up @@ -668,11 +658,11 @@ public void onTextChanged(CharSequence s, int start, int before, int count) {
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();

FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setCountry(mCountryCodePicker.getSelectedCountryNameCode().toLowerCase())
.setTypeFilter(TypeFilter.CITIES)
.setSessionToken(token)
.setQuery(edCity.getText().toString())
.build();
.setCountry(mCountryCodePicker.getSelectedCountryNameCode().toLowerCase())
.setTypeFilter(TypeFilter.CITIES)
.setSessionToken(token)
.setQuery(edCity.getText().toString())
.build();

placesClient.findAutocompletePredictions(request).addOnSuccessListener(response -> {
city_progressBar.setVisibility(View.GONE);
Expand Down Expand Up @@ -724,7 +714,7 @@ public void afterTextChanged(Editable s) {
});

unidentifiedCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(unidentifiedCheckBox.isChecked()) {
if (unidentifiedCheckBox.isChecked()) {
linearLayoutName.setVisibility(View.GONE);
relativeLayoutDOB.setVisibility(View.GONE);
linearLayoutContactInfo.setVisibility(View.GONE);
Expand All @@ -745,14 +735,19 @@ public void performFunction(int position) {
StrictMode.setVmPolicy(builder.build());
AddEditPatientFragmentPermissionsDispatcher.capturePhotoWithCheck(AddEditPatientFragment.this);
} else if (position == 1) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ApplicationConstants.RequestCodes.GALLERY_IMAGE_REQUEST);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
return;
}

Intent i;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
else
i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(i, GALLERY_IMAGE_REQUEST);
startActivityForResult(i, ApplicationConstants.RequestCodes.GALLERY_IMAGE_REQUEST);
} else {
patientImageView.setImageResource(R.drawable.ic_person_grey_500_48dp);
patientImageView.invalidate();
Expand All @@ -767,29 +762,29 @@ public void capturePhoto() {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output = new File(dir, getUniqueImageFileName());
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(takePictureIntent, IMAGE_REQUEST);
startActivityForResult(takePictureIntent, ApplicationConstants.RequestCodes.IMAGE_REQUEST);
}
}

@OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
public void showRationaleForCamera(final PermissionRequest request) {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.permission_camera_rationale)
.setPositiveButton(R.string.button_allow, (dialog, which) -> request.proceed())
.setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
.show();
.setMessage(R.string.permission_camera_rationale)
.setPositiveButton(R.string.button_allow, (dialog, which) -> request.proceed())
.setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
.show();
}

@OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
public void showDeniedForCamera() {
createSnackbarLong(R.string.permission_camera_denied)
.show();
.show();
}

@OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
public void showNeverAskForCamera() {
createSnackbarLong(R.string.permission_camera_neverask)
.show();
.show();
}

private Snackbar createSnackbarLong(int stringId) {
Expand All @@ -802,34 +797,39 @@ private Snackbar createSnackbarLong(int stringId) {

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST) {
if (requestCode == ApplicationConstants.RequestCodes.IMAGE_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
patientPhoto = getResizedPortraitImage(output.getPath());
Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight());
patientImageView.setImageBitmap(bitmap);
patientImageView.invalidate();
Uri sourceUri = Uri.fromFile(output);
openCropActivity(sourceUri, sourceUri);
} else {
output = null;
}
} else if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {

try {
ParcelFileDescriptor parcelFileDescriptor =
getActivity().getContentResolver().openFileDescriptor(data.getData(), ApplicationConstants.READ_MODE);
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();

patientPhoto = image;
} else if (requestCode == ApplicationConstants.RequestCodes.IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
rishabh-997 marked this conversation as resolved.
Show resolved Hide resolved
Uri sourceUri = data.getData();
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output = new File(dir, getUniqueImageFileName());
Uri destinationUri = Uri.fromFile(output);
openCropActivity(sourceUri, destinationUri);
} else if (requestCode == UCrop.REQUEST_CROP) {
if (resultCode == Activity.RESULT_OK) {
patientPhoto = getResizedPortraitImage(output.getPath());
Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight());
patientImageView.setImageBitmap(bitmap);
patientImageView.invalidate();
} catch (Exception e) {
logger.e("Error getting image from gallery.", e);
} else {
output = null;
}
} else if (requestCode == UCrop.RESULT_ERROR) {
ToastUtil.error(String.valueOf(UCrop.getError(data)));
}
}

private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.of(sourceUri, destinationUri)
.withAspectRatio(ApplicationConstants.ASPECT_RATIO_FOR_CROPPING, ApplicationConstants.ASPECT_RATIO_FOR_CROPPING)
.start(getActivity(), AddEditPatientFragment.this);
}

private String getUniqueImageFileName() {
// Create an image file name
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Expand Down Expand Up @@ -937,4 +937,11 @@ private void resetAction() {
updatedPatient = null;
output = null;
}

@Retention(SOURCE)
@StringDef({StringValue.MALE, StringValue.FEMALE})
public @interface StringValue {
String FEMALE = "F";
String MALE = "M";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public abstract class ApplicationConstants {
public static final String BUNDLE = "bundle";
public static final String URI_CONTENT = "content://";
public static final String MIME_TYPE_VND = "vnd";
public static final float ASPECT_RATIO_FOR_CROPPING = 5f;

public abstract static class OpenMRSSharedPreferenceNames {
public static final String SHARED_PREFERENCES_NAME = "shared_preferences";
Expand Down Expand Up @@ -133,6 +134,8 @@ public abstract static class RequestCodes {
public static final int ADD_PROVIDER_REQ_CODE = 100;
public static final int EDIT_PROVIDER_REQ_CODE = 101;
public static final int START_SETTINGS_REQ_CODE = 102;
public final static int IMAGE_REQUEST = 1;
public final static int GALLERY_IMAGE_REQUEST = 2;
}

public abstract static class OpenMRSThemes {
Expand Down