resultCode always 0/RESULT_CANCELED on startActivityForResult when Take a Picture - android

I want to take a picture without crop and I follow tutorial from Developer Android. This is my class:
Fisrt, I make dialog to show and to get the picture.
public void uploadPO() {
final Dialog d = new Dialog(TransDetailActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.getWindow().setBackgroundDrawable(new ColorDrawable((Color.TRANSPARENT)));
d.setContentView(R.layout.upload_po);
final ImageView ivImage1 = (ImageView) d.findViewById(R.id.iv_image1);
final ImageView ivImage2 = (ImageView) d.findViewById(R.id.iv_image2);
final ImageView ivImage3 = (ImageView) d.findViewById(R.id.iv_image3);
final ImageView ivImage4 = (ImageView) d.findViewById(R.id.iv_image4);
ivImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 1;
}
});
ivImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 2;
}
});
ivImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 3;
}
});
ivImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 4;
}
});
d.show();
}
Next, i make method for chosing take a photo or choose from gallery.
private void selectImagePO() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo PO!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
selectFrom(PICK_FROM_CAMERA);
/*Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);*/
} else if (options[item].equals("Choose from Gallery")) {
selectFrom(PICK_FROM_GALLERY);
/*Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);*/
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Next, based on previous selection, I made a function in accordance with the selection.
private void selectFrom(int from) {
if (from == PICK_FROM_CAMERA) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
}
} else {
if(Build.VERSION.SDK_INT <19) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
}else{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
}
}
}
And, i get the error in this class.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Toast.makeText(getActivity(),""+resultCode+"", Toast.LENGTH_SHORT).show();
if (resultCode == RESULT_OK) {
if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap imageBitmap = (Bitmap) extras.get("data");
/*Picasso.with(this)
.load()
.transform(new CircleTransform())
.into(imageProfile);*/
if(statusOnUpload == 1){
ivImage1.setImageBitmap(imageBitmap);
} else if(statusOnUpload == 2){
ivImage2.setImageBitmap(imageBitmap);
}else if(statusOnUpload == 3){
ivImage3.setImageBitmap(imageBitmap);
}else{
ivImage4.setImageBitmap(imageBitmap);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
if (statusOnUpload == 1) {
encodedImageString1 = Base64.encodeToString(b, Base64.NO_WRAP);
Log.d(TAG, encodedImageString1.toString());
} else if (statusOnUpload == 2) {
encodedImageString2 = Base64.encodeToString(b, Base64.NO_WRAP);
} else if (statusOnUpload == 3) {
encodedImageString3 = Base64.encodeToString(b, Base64.NO_WRAP);
} else if (statusOnUpload == 4) {
encodedImageString4 = Base64.encodeToString(b, Base64.NO_WRAP);
}
//Log.i("")
//Toast.makeText(getApplicationContext(),""+encodedImageString+"",Toast.LENGTH_SHORT).show();
//DialogDeal dialogDeal=new DialogDeal(EditProfileActivity.this,"imageBase64",encodedImageString,"Cancel");
//dialogDeal.show();
} else {
//LogManager.logI("extras == null");
}
} else if (requestCode == PICK_FROM_GALLERY) {
mImageCaptureUri = data.getData();
doCrop();
}
}
}
What's the problem of my development?

First make sure you the correct permissions in your manifest. I know you're using a camera app as a service, but I think you may need:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
If that doesn't help you may want to try using this class below. Dealing with hardware like camera is never simple. I suggest using this base activity. I found it somewhere a long time ago here on SO. It handles some fragmentation issues.
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.Date;
import java.util.Locale;
public abstract class BaseCameraIntentActivity extends BaseActivity
{
private static final String PACKAGE_NAME = "com.your.package";
private static final String DATE_CAMERA_INTENT_STARTED_STATE =
PACKAGE_NAME+"dateCameraIntentStarted";
private static final String CAMERA_PIC_URI_STATE =
PACKAGE_NAME+"CAMERA_PIC_URI_STATE";
private static final String PHOTO_URI_STATE =
PACKAGE_NAME+"PHOTO_URI_STATE";
private static final String ROTATE_X_DEGREES_STATE =
PACKAGE_NAME+"ROTATE_X_DEGREES_STATE";
/**
* Date and time the camera intent was started.
*/
protected static Date dateCameraIntentStarted = null;
/**
* Default location where we want the photo to be ideally stored.
*/
protected static Uri preDefinedCameraUri = null;
/**
* Potential 3rd location of photo data.
*/
protected static Uri photoUriIn3rdLocation = null;
/**
* Retrieved location of the photo.
*/
protected static Uri photoUri = null;
/**
* Orientation of the retrieved photo.
*/
protected static int rotateXDegrees = 0;
private final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
/**
* Saves the current state of the activity.
*/
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (dateCameraIntentStarted != null) {
savedInstanceState.putString(
DATE_CAMERA_INTENT_STARTED_STATE,
DateHelper.dateToString(dateCameraIntentStarted));
}
if (preDefinedCameraUri != null) {
savedInstanceState.putString(
CAMERA_PIC_URI_STATE,
preDefinedCameraUri.toString());
}
if (photoUri != null) {
savedInstanceState.putString(
PHOTO_URI_STATE,
photoUri.toString());
}
savedInstanceState.putInt(
ROTATE_X_DEGREES_STATE,
rotateXDegrees);
}
/**
* Re-initializes a saved state of the activity.
*/
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey(DATE_CAMERA_INTENT_STARTED_STATE)) {
dateCameraIntentStarted = DateHelper.stringToDate(
savedInstanceState.getString(DATE_CAMERA_INTENT_STARTED_STATE));
}
if (savedInstanceState.containsKey(CAMERA_PIC_URI_STATE)) {
preDefinedCameraUri = Uri.parse(savedInstanceState.getString(CAMERA_PIC_URI_STATE));
}
if (savedInstanceState.containsKey(PHOTO_URI_STATE)) {
photoUri = Uri.parse(savedInstanceState.getString(PHOTO_URI_STATE));
}
rotateXDegrees = savedInstanceState.getInt(ROTATE_X_DEGREES_STATE);
}
/**
* Starts the camera intent depending on the device configuration.
* <p/>
* <b>for Samsung and Sony devices:</b>
* We call the camera activity with the method call to startActivityForResult.
* We only set the constant CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE. We do NOT set any other intent extras.
* <p/>
* <b>for all other devices:</b>
* We call the camera activity with the method call to startActivityForResult as previously.
* This time, however, we additionally set the intent extra MediaStore.EXTRA_OUTPUT
* and provide an URI, where we want the image to be stored.
* <p/>
* In both cases we remember the time the camera activity was started.
*/
public void startCameraIntent()
{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
// NOTE: Do NOT SET: intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri)
// on Samsung Galaxy S2/S3/.. for the following reasons:
// 1.) it will break the correct picture orientation
// 2.) the photo will be stored in two locations (the given path and, additionally, in the MediaStore)
String manufacturer = android.os.Build.MANUFACTURER.toLowerCase(Locale.ENGLISH);
String model = android.os.Build.MODEL.toLowerCase(Locale.ENGLISH);
String buildType = android.os.Build.TYPE.toLowerCase(Locale.ENGLISH);
String buildDevice = android.os.Build.DEVICE.toLowerCase(Locale.ENGLISH);
String buildId = android.os.Build.ID.toLowerCase(Locale.ENGLISH);
// String sdkVersion = android.os.Build.VERSION.RELEASE.toLowerCase(Locale.ENGLISH);
boolean setPreDefinedCameraUri = false;
if (!(manufacturer.contains("samsung")) && !(manufacturer.contains("sony"))) {
setPreDefinedCameraUri = true;
}
if (manufacturer.contains("samsung") && model.contains("galaxy nexus")) { //TESTED
setPreDefinedCameraUri = true;
}
if (manufacturer.contains("samsung") && model.contains("gt-n7000") && buildId.contains("imm76l")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("ariesve")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("crespo")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9100")) { //TESTED
setPreDefinedCameraUri = true;
}
///////////////////////////////////////////////////////////////////////////
// TEST
if (manufacturer.contains("samsung") && model.contains("sgh-t999l")) { //T-Mobile LTE enabled Samsung S3
setPreDefinedCameraUri = true;
}
if (buildDevice.contains("cooper")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("t0lte")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("kot49h")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("t03g")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9300")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9195")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("xperia u")) {
setPreDefinedCameraUri = true;
}
///////////////////////////////////////////////////////////////////////////
dateCameraIntentStarted = new Date();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (setPreDefinedCameraUri) {
// String filename = ImageConfig.getTempFileName();
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
preDefinedCameraUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, preDefinedCameraUri);
}
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
logException(e);
onCouldNotTakePhoto();
}
} else {
onSdCardNotMounted();
}
}
/**
* Receives all activity results and triggers onCameraIntentResult if
* the requestCode matches.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE: {
onCameraIntentResult(requestCode, resultCode, intent);
break;
}
}
}
/**
* On camera activity result, we try to locate the photo.
* <p/>
* <b>Mediastore:</b>
* First, we try to read the photo being captured from the MediaStore.
* Using a ContentResolver on the MediaStore content, we retrieve the latest image being taken,
* as well as its orientation property and its timestamp.
* If we find an image and it was not taken before the camera intent was called,
* it is the image we were looking for.
* Otherwise, we dismiss the result and try one of the following approaches.
* <b>Intent extra:</b>
* Second, we try to get an image Uri from intent.getData() of the returning intent.
* If this is not successful either, we continue with step 3.
* <b>Default photo Uri:</b>
* If all of the above mentioned steps did not work, we use the image Uri we passed to the camera activity.
*
* #param requestCode
* #param resultCode
* #param intent
*/
protected void onCameraIntentResult(int requestCode, int resultCode, Intent intent)
{
if (resultCode == RESULT_OK) {
Cursor myCursor = null;
Date dateOfPicture = null;
try {
// Create a Cursor to obtain the file Path for the large image
String[] largeFileProjection = {MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.Images.ImageColumns.DATE_TAKEN};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection,
null, null,
largeFileSort);
myCursor.moveToFirst();
if (!myCursor.isAfterLast()) {
// This will actually give you the file path location of the image.
String largeImagePath = myCursor.getString(
myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
);
photoUri = Uri.fromFile(new File(largeImagePath));
if (photoUri != null) {
dateOfPicture = new Date(
myCursor.getLong(
myCursor.getColumnIndexOrThrow(
MediaStore.Images.ImageColumns.DATE_TAKEN)));
if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) {
rotateXDegrees = myCursor.getInt(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
} else {
photoUri = null;
}
}
if (myCursor.moveToNext() && !myCursor.isAfterLast()) {
String largeImagePath3rdLocation = myCursor.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
Date dateOfPicture3rdLocation = new Date(
myCursor.getLong(myCursor.getColumnIndexOrThrow(
MediaStore.Images.ImageColumns.DATE_TAKEN))
);
if (dateOfPicture3rdLocation != null && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) {
photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation));
}
}
}
} catch (Exception e) {
logException(e);
} finally {
if (myCursor != null && !myCursor.isClosed()) {
myCursor.close();
}
}
if (photoUri == null) {
try {
photoUri = intent.getData();
} catch (Exception e) {
}
}
if (photoUri == null) {
photoUri = preDefinedCameraUri;
}
try {
if (photoUri != null && new File(photoUri.getPath()).length() <= 0) {
if (preDefinedCameraUri != null) {
Uri tempUri = photoUri;
photoUri = preDefinedCameraUri;
preDefinedCameraUri = tempUri;
}
}
} catch (Exception e) {
}
photoUri = getFileUriFromContentUri(photoUri);
preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri);
try {
if (photoUriIn3rdLocation != null) {
if (photoUriIn3rdLocation.equals(photoUri)
|| photoUriIn3rdLocation.equals(preDefinedCameraUri)) {
photoUriIn3rdLocation = null;
} else {
photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation);
}
}
} catch (Exception e) {
}
if (photoUri != null) {
onPhotoUriFound();
} else {
onPhotoUriNotFound();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
onCanceled();
} else {
onCanceled();
}
}
/**
* Being called if the photo could be located. The photo's Uri
* and its orientation could be retrieved.
*/
protected void onPhotoUriFound()
{
logMessage("Your photo is stored under: " + photoUri.toString());
}
/**
* Being called if the photo could not be located (Uri == null).
*/
protected void onPhotoUriNotFound()
{
logMessage("Could not find a photoUri that is != null");
}
/**
* Being called if the camera intent could not be started or something else went wrong.
*/
protected void onCouldNotTakePhoto()
{
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
/**
* Being called if the SD card (or the internal mass storage respectively) is not mounted.
*/
protected void onSdCardNotMounted()
{
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
/**
* Being called if the camera intent was canceled.
*/
protected void onCanceled()
{
logMessage("Camera Intent was canceled");
}
/**
* Logs the passed exception.
*
* #param exception
*/
protected void logException(Exception exception)
{
logMessage(exception.toString());
}
/**
* Logs the passed exception messages.
*
* #param exceptionMessage
*/
protected void logMessage(String exceptionMessage)
{
Log.d(getClass().getName(), exceptionMessage);
}
/**
* Given an Uri that is a content Uri (e.g.
* content://media/external/images/media/1884) this function returns the
* respective file Uri, that is e.g. file://media/external/DCIM/abc.jpg
*
* #param cameraPicUri
* #return Uri
*/
private Uri getFileUriFromContentUri(Uri cameraPicUri)
{
try {
if (cameraPicUri != null
&& cameraPicUri.toString().startsWith("content")) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(cameraPicUri, proj, null, null, null);
cursor.moveToFirst();
// This will actually give you the file path location of the image.
String largeImagePath = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
cursor.close();
return Uri.fromFile(new File(largeImagePath));
}
return cameraPicUri;
} catch (Exception e) {
return cameraPicUri;
}
}
}

Related

How to set filename to textview in android

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);
}
}
}

Is disappearing after going to another activity but showing uploading to server Glide and volley

I have created two functionality for photo uploading in my app. The first one is for capture image and the second one is for pick image from gallery. Now I have a photo API as URL. By using this API I have to upload the image at first to server and from server it will be available throught the app. Now I can successfully uploaded the picture in server and in the server side shows the picture. But in the imageview of app does not show that image. Whenever I go to another activity and then come back to image activity the imageview is empty. I have used shared preference to keep the image at image view, but that does not work.
Here is my code for photo activity
public class ViewProfileFragment extends Fragment implements
View.OnClickListener{
private static final int CODE_GALLERY_REQUEST =999 ;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private ImageView image;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
Bitmap bm;
private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_view_profile,
container, false);
.........
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
Log.d( "----ViewProfile-Email", "mEmail" );
GlobalClass globalClass = new GlobalClass();
String mEmail = globalClass.getEmail_info();
Realm profileRealm;
profileRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results =
profileRealm.where(MyColleagueModel.class).equalTo("mail",
mEmail).findAll();
//fetching the data
results.load();
if (results.size() > 0) {
......
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions,grantResults );
}
public void showDialog(){
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new
AlertDialog.Builder(this.getActivity());
.....
}
});
alertListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
File cameraFolder;
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new
File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri,
projection, null, null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
imageMaxQuality, imageMinQuality, maxSize);
File destination = new
File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
private void uploadImage(final byte[] bytesArray){
.....
}
}
Please don't use
image.setImageURI(uri);
image.invalidate();
Please use this code below instead of that :
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}

How to await OnActivityResult in Xamarin C# on Android

I'm using MvvmCross on Android via Xamarin and i got a problem. I created a core service interface called IFileExplorerService.
This interface goal is to open a open file dialog and select a file whatever the device is (Windows or android).
On android i managed easly to do this without my interface via view by just using the OnActivityResult and Intents.
But i just cannot make it work from my view, as the interface implementation is a singleton registered in the setup, when i call it from my viewmodel there is absolutely no one to handle the OnActivityResult.
I tried to make my FileExplorer implmentation to inherit from Activity or MvxActivity, for this way my FileExplorer could override OnActivityResult, but this fails.
I tried to use StartActivity(typeof(FileExplorer)) but this obviously would fails anyway as it wouldn't be the singleton registered in MvvmCross that would be started.
Does anyone has any idea/comment/question/suggestion to help me on this?
Here is my code so far :
public class FileExplorerService : IFileExplorerServiceMock
{
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public Activity activity;
public FileExplorerService()
{
GetFileTask = new TaskCompletionSource<string>();
}
private void DispatchSelectFileIntent()
{
Intent Intent = new Intent();
Intent.SetType("*/*");
Intent.SetAction(Intent.ActionGetContent);
activity.StartActivityForResult(Intent.CreateChooser(Intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return GetFileTask.Task.Result;
}
else
{
return String.Empty;
}
}
And in my view :
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.RexView);
_addMediaController = new AddMediaController(this, (RexViewModel)base.ViewModel);
_flyoutMenuAnimator = new FlyoutMenuAnimator(this);
var t= Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.activity = this;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
var t = Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.OnActivityResult(requestCode, resultCode, data);
base.OnActivityResult(requestCode, resultCode, data);
}
With this everything work except that OnActivityResult is never called in my view
Okay i solved it ! Thanks to this link https://forums.xamarin.com/discussion/45691/pass-data-from-android-project-to-pcl
I had to rewrite start activity to give it a callback as an argument, the callback being my OnActivityResult in my file Explorer.
Here is my the code for anyone needing it :
in MyView:
private Action<int, Result, Intent> _resultCallback;
public void StartActivity(Intent intent,int resultCode, Action<int, Result, Intent> resultCallback)
{
_resultCallback = resultCallback;
StartActivityForResult(intent, resultCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (_resultCallback != null)
{
_resultCallback(requestCode, resultCode, data);
_resultCallback = null;
}
}
and in my file Explorer :
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public RexView activity;
public FileExplorerService()
{
}
private void DispatchSelectFileIntent()
{
Intent intent = new Intent();
intent.SetType("*/*");
intent.SetAction(Intent.ActionGetContent);
GetFileTask = new TaskCompletionSource<string>();
activity.StartActivity(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE, OnActivityResult);
// activity.StartActivityForResult(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return await GetFileTask.Task;
}
else
{
return String.Empty;
}
}
}
And in my view model
private async void BrowseMedias()
{
var fileExplorerService = Mvx.Resolve<IFileExplorerServiceMock>();
fileExplorerService.FileTypes.Add(FileType.Picture);
string fileSavedPath = await fileExplorerService.Show(DatabaseContentPath);
/* file managment*/
}

Activity associated with image cropping libraries does not destroy

I have tried to solve this problem from many different links but does not worked for me.I am using Android Image Cropper library for cropping images. Whenever i click on the button "upload image" it start the cropping activity and when i am done the cropped image is set in an imageview in "upload image" activity and after clicking "Proceed" button login is successful and i am directed to login activity but when i back press the login activity the "Upload image" activity is still there and is not destroyed. I have another activity called Update Activity that uses this Cropping activity and that activity also behaves in the same manner. So i want the "Upload image" to destroy. Thanks in advance
package com.donateblood.blooddonation;
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (Foolish android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
package com.donateblood.blooddonation;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
code = (EditText) findViewById(R.id.code);
ButterKnife.inject(this);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
// set the image
// myimage = getRoundedShape(myimage);
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Picasso.with(UploadImage.this).load(file).resize(200,200).placeholder(R.drawable.user).error(R.drawable.error)
.transform(new CircleTransform()).centerCrop()
.into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
// resize the image to store to database
//myimage= getResizedBitmap(myimage,200,200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Wrong code or No image uploaded", Toast.LENGTH_LONG).show();
}
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json =null;
boolean added = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
userDetails.put("ID",ID);
userDetails.put("Name",name);
userDetails.put("email",email);
userDetails.put("password",password);
userDetails.put("age",age);
userDetails.put("number",number);
userDetails.put("bloodgroup",bloodgroup);
userDetails.put("lat",latitude+"");
userDetails.put("longi",longitude+"");
userDetails.put("image",encodedPhotoString);
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/Adduser.php",userDetails);
if(json!=null){
added = true;
}else {
added = false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if(added==true){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Error creating account. Try again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
check this method you are not finishing the UploadActivity here:-
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadActivity.this.finish();
}
});

Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery

Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.
below is my code
public class CaptureImageActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ICS Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(fileUri.getPath());
System.out.println("PATH " + fileUri.getPath());
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent1, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* Recording video
*/
private void recordVideo() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent1.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image
// file
// name
// start the video capture Intent
startActivityForResult(intent1, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
// Uri.parse(fileUri.getPath())));
System.out.println("RESULT OK");
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo() {
try {
System.out.println("PATH " + fileUri.getPath());
getContentResolver().notifyChange(Uri.parse(fileUri.getPath()),
null);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
// mc.setMediaPlayer(videoPreview);
// hide image preview
// videoPreview.setOnPreparedListener(new OnPreparedListener() {
//
// public void onPrepared(MediaPlayer mp) {
// // TODO Auto-generated method stub
// mp.start();
// }
// });
imgPreview.setVisibility(View.GONE);
// getWindow().clearFlags(
// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
videoPreview.setVisibility(View.VISIBLE);
// 02-15 11:51:52.973: I/System.out(17840): PATH
// /mnt/sdcard/Pictures/ICS Camera/VID_20140215_115133.mp4
videoPreview.setVideoPath(fileUri.getPath());
// videoPreview.setVideoURI(Uri.parse(Provoder.CONTENT_URI_BASE
// + Uri.encode(fileUri.getPath())));
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Solved my issue by using below code
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.kubical.ES.R;
import com.kubical.ES.util.ApplicationConstants;
public class CaptureImageActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
private String filePath;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(filePath);
System.out.println("PATH " + filePath);
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Recording video
*/
private void recordVideo() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent1, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
previewCapturedImage(data);
} else if (resultCode == RESULT_CANCELED) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
previewVideo(data);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage(Intent data) {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
System.out.println("PATH IS " + filePath);
cursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo(Intent data) {
try {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(column_index);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(filePath);
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources