I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);
Related
I have a question about upload image to firebase and it works before and after I done other activity...It failed...Can your guys help me...
The main error was when user click OK or CANCEL in confirmation page, the app crash. App will crash too when user select from gallery...
Here is the logcat...
2021-03-30 22:56:16.853 12576-12576/? E/in.firebasetes: Unknown bits set in runtime_flags: 0x8000
And here is the code for activity...
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users");
userID = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference();
UserPic = (ImageView) findViewById(R.id.UserPic);
UserPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPermission();
}
if (user != null){
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl()).into(UserPic);
}
}
}
private void VerifyPermission() {
if (ContextCompat.checkSelfPermission(UserProfile.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UserProfile.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
}else {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
selectOptionList();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectOptionList();
}else {
Toast.makeText(UserProfile.this, "Camera Permissions is required", Toast.LENGTH_LONG).show();
}
}
}
private void selectOptionList(){
selectList = getResources().getStringArray(R.array.selectList);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an option");
builder.setItems(selectList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
dispatchTakePictureIntent();
break;
case 1:
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_REQUEST_CODE);
break;
case 2:
dialog.dismiss();
break;
}
}
});
alertDialog = builder.create();
builder.show();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "interpayment.main.firebasetest.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + userID + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
Toast.makeText(UserProfile.this, "Opening Camera", Toast.LENGTH_SHORT).show();
return image;
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference img = storageReference.child("pictures/" + name);
img.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
img.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d("100", "onSuccess: Upload Image URL is " + uri);
Toast.makeText(UserProfile.this, "Uploaded", Toast.LENGTH_SHORT).show();
setUserProfileUrl(uri);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void setUserProfileUrl(Uri uri) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest request = new UserProfileChangeRequest.Builder().setPhotoUri(uri).build();
user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserProfile.this, "Updated", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Failed set Profile", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE) {
File f = new File(currentPhotoPath);
UserPic.setImageURI(Uri.fromFile(f));
Log.d("tag", "Absolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}else if(requestCode == GALLERY_REQUEST_CODE && data != null){
Uri img = data.getData();
Log.d("tag", "onActivityResult: Gallery Image Uri: " + img);
UserPic.setImageURI(img);
uploadImageToFirebase(currentPhotoPath, img);
}
}
}
I appreciate for your guys helping and thanks a lot for taking time to help me. Logcat was like this...
Logcat
----------------------------------------------------------------------
Update
My question is solved. The problem was the onStop function, I removed it. This is because the system set the [open camera] and [take photo from gallery] as new actitvity. So, if you have the onStop function, system close the apps when you open camera or others. This cause the apps automatically close and no any error in logcat.
Hi in the below code I am using one button named as choose file. If users click on choose file button showing three options like take a photo, gallery, cancel. Suppose click on take a photo open a camera and taking a photo and then want to set the image name to my textview.
the same feature wants to applicable to the gallery also.
Example :
If I am taking a photo from camera image name abc.jpeg
Gallery also image name
Can anyone help me?
public class OpportunityCreateFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the borderdashboard for this fragment
View rootView = inflater.inflate(R.layout.opportunity_form, container, false);
Textview no_file_pan=rootview.findViewById(R.id.no_file_pan);
pan_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Gallery",
"Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
requestStoragePermission(true);
} else if (items[item].equals("Choose from Gallery")) {
requestStoragePermission(false);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* Capture image from camera
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
mPhotoFile = photoFile;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
/**
* Select image fro gallery
*/
private void dispatchGalleryIntent() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickPhoto.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(pickPhoto, REQUEST_GALLERY_PHOTO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO) {
try {
mPhotoFile = mCompressor.compressToFile(mPhotoFile);
no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
} catch (IOException e) {
e.printStackTrace();
}
// Glide.with(getActivity()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);
} else if (requestCode == REQUEST_GALLERY_PHOTO) {
Uri selectedImage = data.getData();
try {
mPhotoFile = mCompressor.compressToFile(new File(getRealPathFromUri(selectedImage)));
no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
} catch (IOException e) {
e.printStackTrace();
}
//Glide.with(getApplicationContext()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);
}
}
}
/**
* Requesting multiple permissions (storage and camera) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestStoragePermission(final boolean isCamera) {
Dexter.withActivity((Activity) getContext()).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
if (isCamera) {
dispatchTakePictureIntent();
} else {
dispatchGalleryIntent();
}
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getActivity().getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
/**
* Create file with current timestamp name
*
* #return
* #throws IOException
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String mFileName = "PAN"+"_";
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File mFile = File.createTempFile(mFileName, ".jpg", storageDir);
return mFile;
}
/**
* Get real file path from URI
*
* #param contentUri
* #return
*/
public String getRealPathFromUri(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContext().getContentResolver().query(contentUri, proj, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
return rootView;
}
Use this method :
public String getFileName(File file) {
if (file == null) return "";
String fileName = "";
String path = file.getAbsolutePath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
And call like this :
no_file_pan.setText(getFileName(mPhotoFile));
Try this
no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
Use this helpful library to pick image from gallery and take picture from camera
https://github.com/esafirm/android-image-picker
Note:-
Remove this no_file_pan.setText(mPhotoFile.getName()); from
dispatchTakePictureIntent() method like this
/**
* Capture image from camera
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
mPhotoFile = photoFile;
// no_file_pan.setText(mPhotoFile.getName()); //remove or comment this line because file has not been created yet, better to set text in onActivity result
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
I want to display the image I took inside an imageview but it doesn't display the image. I checked these pages but got no results:
Image captured from camera not displaying in imageview android
Capture Image from Camera and Display in Activity
my activity:
public class MainActivity extends AppCompatActivity {
Button btncam;
ImageView imgpic;
final int take=10;
long name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgpic=(ImageView)findViewById(R.id.imgpic);
btncam=(Button)findViewById(R.id.btncamera);
btncam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
name=System.currentTimeMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(G.appadress+"/"+name+".jpg")));
startActivityForResult(intent,take);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode){
case take:
Bitmap bitmap= BitmapFactory.decodeFile(G.appadress+"/"+name+".jpg");
imgpic.setImageBitmap(bitmap);
}
}
}
class G:
public class G extends Application {
public static Context context;
public static String appadress= Environment.getExternalStorageDirectory().getAbsolutePath();
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
File file=new File(appadress);
file.mkdirs();
}
}
manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try:
public class MainActivity extends AppCompatActivity {
Button btncam;
ImageView imgpic;
final int take = 10;
Bitmap bitmap;
long name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgpic = (ImageView) findViewById(R.id.imgpic);
btncam = (Button) findViewById(R.id.btncamera);
btncam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras() != null) {
bitmap = (Bitmap) data.getExtras().get("data");
try {
File imageFile = createImageFile();
OutputStream stream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
imgpic.setImageBitmap(bitmap);
}
}
}
public File createImageFile() throws IOException {
// Create an imageView file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getStorageDir();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpeg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
return image;
}
private File getStorageDir() {
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/PathPhoto"); //Environment.DIRECTORY_PICTURES -->> it is path for Pictures
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
return storageDir;
}
}
I prefer Android Image Cropper library, automatically handles Importing or Capturing images.
private void onCaptureClick(){
CropImage.activity()
.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 resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
class G:
public class G extends Application {
public static Context context;
public static String appadress= Environment.getExternalStorageDirectory().getAbsolutePath()+"/reza";
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
File file=new File(appadress);
file.mkdirs();
}
}
I am building an app to upload images to my company server
I am using koush-ion for the upload,
now my problem is I have to dynamically change the URL for upload depending on information entered in another activity(LoginActivity) via edittext boxes
and I don't understand how to do that
so what I want to happen is the client enters thier Email, password and clientID(4 digits)(in LoginActivity) and the app uses that to build a url for the upload
like this one(in CameraActivity)
https://www.blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes&ClientID=1234&Username=man#blahpractice.co.za&Pwd=BlahBlah123#
I got this From the koush github, and i am unsure if this is what i am looking for and also how to implement data from another activity in koush-ion
Post application/x-www-form-urlencoded and read a String
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)
Camera Activity
public class CameraActivity extends AppCompatActivity implements
View.OnClickListener{
private final int PICK_IMAGE = 12345;
private final int REQUEST_CAMERA = 6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION =5674;
private Bitmap bitmap;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView =findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
fromCamera.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
}else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
I want to call the url here
File imageFile = persistImage(bitmap, "SP_Upload");
Ion.with(this)
.load("https://www.Blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes")
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir = getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailAddress=email.getText().toString().trim();
String userPassword=password.getText().toString().trim();
String clientId=id.getText().toString().trim();
Intent intent=new Intent(LoginActivity.this, CameraActivity.class);
intent.putExtra("clientId", clientId);
intent.putExtra("email", emailAddress);
intent.putExtra("password", userPassword);
startActivity(intent);
}
});
}
}
You could store the url on the shared preferences and retrieve it every time you execute your upload task and set it on the .load() method.
Also, what you need to send an image to your server is a multipart post. I haven't used Ion but I have used multipart in other libraries like OkHttp, I´ve copied the method that appears on the Ion documentation:
String dynamicUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(CURRENT_SELECTED_URL, null);
File myImage = new File(myImagePath);
if(dynamicUrl != null) {
Ion.with(getContext())
.load(dynamicUrl)
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("myImageName", "image/*", myImage)
.asJsonObject()
.setCallback(...)
}
excuse me for any grammatical errors.
I made an application that allow you to take a picture and after you clicked "Ok", the picture appear in an ImageView.
Now, I don't know why, when I try this application on my Nexus 5X, the photo lose the quality when it appears into the ImageView.
Application image (Image View):
Camera Image:
Fragment Code:
public class CameraFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dispatchTakePictureIntent();
return inflater.inflate(R.layout.fragment_camera,container,false);
}
ImageView SkimmedImageImg;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SkimmedImageImg = (ImageView)view.findViewById(R.id.SkimmedImg);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Fragment CameraFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
CameraFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == REQUEST_IMAGE_CAPTURE){
Bitmap SkimmedImgData = (Bitmap) data.getExtras().get("data");
SkimmedImageImg.setImageBitmap(SkimmedImgData);
}
}
}
}
When you call Bitmap SkimmedImgData = (Bitmap) data.getExtras().get("data");, and then set the image using SkimmedImageImg.setImageBitmap(SkimmedImgData);, you're only setting the thumbnail of the image you took, this is why the quality is so distorted. You can follow this tutorial, which will show you how to save the full size image, look under the header Save the Full-size Photo.
Just copy paste the whole class:
public class CameraFragment extends android.support.v4.app.Fragment{
String mCurrentPhotoPath;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
if (!checkIfAlreadyhavePermission_new()) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
} else {
if (!checkIfAlreadyhavePermission()) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
return inflater.inflate(R.layout.fragment_camera,container,false);
}
ImageView SkimmedImageImg;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SkimmedImageImg = (ImageView)view.findViewById(R.id.SkimmedImg);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() throws IOException {
CameraFragment cameraFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
BuildConfig.APPLICATION_ID + ".provider",
createImageFile());;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
cameraFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
private boolean checkIfAlreadyhavePermission_new() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Uri imageUri = Uri.parse(mCurrentPhotoPath);
File file = new File(imageUri.getPath());
Glide.with(getActivity())
.load(file)
.into(SkimmedImageImg);
// ScanFile so it will be appeared on Gallery
MediaScannerConnection.scanFile(getActivity(),
new String[]{imageUri.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (!checkIfAlreadyhavePermission()) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(getActivity(), "NEED CAMERA PERMISSION", Toast.LENGTH_LONG).show();
}
break;
}
case 2: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "NEED STORAGE PERMISSION", Toast.LENGTH_LONG).show();
}
break;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
If you are getting error while Fragment loading in MainActivity, just use getSupportFragmentManager():
FragmentManager fm = getSupportFragmentManager();