I have a picture that I can change.
I can choose a picture in my gallery or capture a photo.
When I capture a photo, I crop the image.
But the application takes time to crop my photo so I want to show a progressDialog.
My progressDialog appears on my application but it is hidden by the screen where I crop my photo.
How can I make the progressDialog appear inside the screen where I crop my photo ?
Sorry for my bad english...
My code :
public class FragmentMonCompte extends Fragment {
private ImageView ivAvatar;
// YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int CAPTURE_PICTURE = 0;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
// ADDED
private String filemanagerstring;
private Uri mCapturedImageURI;
ProgressDialog mProgressDialog = null;
boolean isPDShow;
Navigation navigation;
Intent data;
Bitmap photo;
Bundle extras;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_compte, container,
false);
ivAvatar = (ImageView) rootView.findViewById(R.id.iv_avatar);
ivAvatar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Navigation navigation = (Navigation) getActivity();
mProgressDialog = new ProgressDialog(navigation);
mProgressDialog.setMessage("Opération en cours...");
mProgressDialog.setTitle("Patientez");
final CharSequence[] items = {"Prendre une photo",
"Choisir une image", "Annuler"};
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Avatar :");
// set dialog message
alertDialogBuilder.setCancelable(false).setItems(items,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,
"");
mCapturedImageURI = navigation
.getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 170);
intent.putExtra("aspectY", 170);
intent.putExtra("outputX", 5000);
intent.putExtra("outputY", 5000);
startActivityForResult(Intent
.createChooser(intent,
"Appareil photo"),
CAPTURE_PICTURE);
}
if (item == 1) {
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 170);
intent.putExtra("aspectY", 170);
intent.putExtra("outputX", 5000);
intent.putExtra("outputY", 5000);
startActivityForResult(Intent
.createChooser(intent,
"Choisir une application"),
SELECT_PICTURE);
}
if (item == 2) {
dialog.cancel();
}
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// afficher
alertDialogBuilder.show();
}
});
return rootView;
}
/**
* Méthode qui permet d'ouvrir la gallery d'images ou l'appareil photo
*
* #param requestCode CAPTURE ou SELECT
* #param resultCode RESULT_OK or not
* #param data Intent
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Navigation navigation = (Navigation) getActivity();
this.navigation = navigation;
this.data = data;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAPTURE_PICTURE) {
isPDShow = true;
if( mProgressDialog!=null && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
new Thread() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
handler.sendEmptyMessage(0);
}
start();
}
};
Bitmap photo = null;
Bundle extras = data.getExtras();
new CapturePhotoAsyncTask().execute((Void) null);
}
if (requestCode == SELECT_PICTURE) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ivAvatar.setImageBitmap(photo);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if( mProgressDialog!=null & mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
/**
* Méthode qui retourne un bitmap compressé
*
* #param c Context de l'application
* #param uri Photo capturée
* #param requiredSize Taille requise
* #return Photo convertie en Bitmap
* #throws FileNotFoundException Fichier non trouvé
*/
public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize)
throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri),
null, o);
int widthTmp = o.outWidth, heightTmp = o.outHeight;
int scale = 1;
while (true) {
if (widthTmp / 2 < requiredSize || heightTmp / 2 < requiredSize) {
break;
}
widthTmp /= 2;
heightTmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(c.getContentResolver()
.openInputStream(uri), null, o2);
}
class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
ivAvatar.setImageBitmap(photo);
mProgressDialog.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
photo = decodeUri(navigation.getApplicationContext(),
mCapturedImageURI, 1000);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}//fin AsyncTask
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
new CapturePhotoAsyncTask().execute((Void) null);
isPDShow = false;
}
};
}
class CapturePhotoAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FragmentMonCompte.this);
pDialog.setMessage("Downloading data");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
ivAvatar.setImageBitmap(photo);
pDialog.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
photo = decodeUri(navigation.getApplicationContext(),
mCapturedImageURI, 1000);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}//fin AsyncTask
Related
I am new to Android application development. Using iText I had done the PDF creation and write on that created file now I want to create image to PDF from my `ImageView. Here's my code :
public class PdfCreatorActivity extends AppCompatActivity {
private static final String TAG = "PdfCreatorActivity";
private EditText mContentEditText;
private Button mCreateButton;
private File pdfFile;
final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
Intent intent;
Uri fileUri;
Button btn_choose_image;
ImageView imageView;
Bitmap bitmap, decoded;
public final int REQUEST_CAMERA = 0;
public final int SELECT_FILE = 1;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfcreator);
btn_choose_image = (Button) findViewById(R.id.btn_choose_image);
imageView = (ImageView) findViewById(R.id.image_view);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mContentEditText = (EditText) findViewById(R.id.edit_text_content);
mCreateButton = (Button) findViewById(R.id.button_create);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContentEditText.getText().toString().isEmpty()){
mContentEditText.setError("Body is empty");
mContentEditText.requestFocus();
return;
}
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
});
}
private void selectImage() {
imageView.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(PdfCreatorActivity.this);
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeFile(fileUri.getPath());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// mengambil gambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(PdfCreatorActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Untuk menampilkan bitmap pada ImageView
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// Untuk resize bitmap
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DeKa");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_DeKa_" + timeStamp + ".jpg");
return mediaFile;
}
}
This Code for Create PDF
private void createPdfWrapper() throws FileNotFoundException,DocumentException{
int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
showMessageOKCancel("You need to allow access to Storage",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
});
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
return;
}else {
createPdf();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
} else {
// Permission Denied
Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private void createPdf() throws FileNotFoundException, DocumentException {
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
pdfFile = new File(docsFolder.getAbsolutePath(),"HelloWorld.pdf");
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
document.add(new Paragraph(mContentEditText.getText().toString()));
document.close();
previewPdf();
}
private void previewPdf() {
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(pdfFile);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}else{
Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
}
}
I don't know how to implement image can generates to PDF using iText,
Examples will be appreciable...
thanks in advance.
Use PdfDocument to generate pdf form View.
This class enables generating a PDF document from native Android content
Sample code:
// Create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(view.getWidth(), view.getHeight(), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw on page
view.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// generate pdf
new PdfGenerationTask().execute();
Use AsyncTask to generate pdf form document
private class PdfGenerationTask extends AsyncTask<Void, Void, File> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected File doInBackground(Void... params) {
return generatePdf();
}
#Override
protected void onPostExecute(File file) {
/* Dismiss the progress dialog after sharing */
}
}
generatePdf method
private File generatePdf(){
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdf"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pdf";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, pdfName);
if( document != null ){
// write the document content
try {
OutputStream out = new FileOutputStream(file);
if( out != null ){
document.writeTo(out);
// close the document
document.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
PdfDocument is easy and simple to use. PdfDocument required min sdk 19
I have a Bitmap as a general variable to set, but when I run my App, it doesn't show anything.
Here my Code:
public AlertDialog FragmentDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.imagenfoto,null);
dg_image=view.findViewById(R.id.dlg_image);
dg_image.setImageBitmap(bitmap);
builder.setView(inflater.inflate(R.layout.imagenfoto,null))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//dg_image.setImageBitmap(bitmap);
dialogInterface.cancel();
}
});
return builder.create();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode== getActivity().RESULT_OK && requestCode==10){
Uri path=data.getData();
foto.setImageURI(path);
}
*/
if(requestCode==CAMARA_REQUEST && resultCode==Activity.RESULT_OK){
Bitmap photo=(Bitmap)data.getExtras().get("data");
bitmap=(Bitmap)data.getExtras().get("data");
foto.setImageBitmap(photo);
Log.d("Debug",bitmap.toString());
//comunicador.setFoto(bitmap);
/*try {
setFoto(photo);
}catch (Exception e){
Log.d("setGaleria:",e.getMessage());
}*/
//cd_imagen.setImageBitmap(photo);
}
//***//
Uri selectedImageUri=null;
Uri selectedImage;
if(requestCode==SELECT_FILE && resultCode==Activity.RESULT_OK){
selectedImage=data.getData();
String selectedPath=selectedImage.getPath();
if(selectedPath != null){
InputStream imageStream=null;
try {
imageStream=getActivity().getContentResolver().openInputStream(
selectedImage);
}catch (FileNotFoundException e){
e.printStackTrace();
}
//Transformamos la URI de la imagen a ImputStream y este a un Bitmap
Bitmap bmp=BitmapFactory.decodeStream(imageStream);
bitmap=BitmapFactory.decodeStream(imageStream);
Log.d("Debug",bitmap.toString());
/*try {
setFoto(bmp);
}catch (Exception e){
Log.d("setGaleria:",e.getMessage());
}*/
//Ponemos nuestro Bitmap en un ImageView que tengamos en la vista
foto.setImageBitmap(bmp);
//comunicador.setFoto(bmp);
//cd_imagen.setImageBitmap(bmp);
}
}
}
you should pass the view on which you have set the bitmap
not the one using new inflator.
don't pass this
builder.setView(inflater.inflate(R.layout.imagenfoto,null))
instead, use the existing view
builder.setView(view)
Final code
public AlertDialog FragmentDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.imagenfoto,null);
dg_image=view.findViewById(R.id.dlg_image);
dg_image.setImageBitmap(bitmap);
builder.setView(view))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//dg_image.setImageBitmap(bitmap);
dialogInterface.cancel();
}
});
return builder.create();
}
function(element, percentX, percentY){
var tolerance = 0.01; //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
if(percentX == null){
percentX = 100;
}
if(percentY == null){
percentY = 100;
}
var elementRect = element.getBoundingClientRect();
var parentRects = [];
while(element.parentElement != null){
parentRects.push(element.parentElement.getBoundingClientRect());
element = element.parentElement;
}
var visibleInAllParents = parentRects.every(function(parentRect){
var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
var visiblePercentageX = visiblePixelX / elementRect.width * 100;
var visiblePercentageY = visiblePixelY / elementRect.height * 100;
return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
});
return visibleInAllParents;
};
I want to upload image from gallery in my android app. When I click on button, the gallery should be opened. After selecting image, I want to open another activity named UploadActivity. There the thumbnail of the image should be previewed. The Upload Button will below the thumbnail.
But when I Choose photo from gallery, then the thumbnail of the image are not previewing. I am unable to upload the photo also. My Code goes here: (Scan.Java)
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int SELECT_IMAGE = 2;
private Uri fileUri; // file url to store image/video
ImageView dummy;
private Button btnCapturePicture;
private Button btnGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan);
dummy = (ImageView) findViewById(R.id.dummyphoto);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnGallery = (Button) findViewById(R.id.btnGallery);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
btnGallery.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openGallery();
}
});
// 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;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching Gallery to Choose Image
*/
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
/**
* 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 screen 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");
}
/**
* 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
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Scan.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
UploadActivity.Java Code goes here:
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
// Receiving the data from previous activity
Intent i = getIntent();
// image path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
Here is Logcat:
E/MainActivity: Response from server: java.io.FileNotFoundException: /mnt/sdcard/Pictures/master/IMG_20170127_152930.jpg: open failed: ENOENT (No such file or directory)
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "IMG_20170127_152930.jpg");
//Try this.
After these changes i suggested below I hope your problem will be solved:
Remove these two lines from openGallery() because I think they are redundant.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
They are needed when we use Intent.ACTION_PICK. So after editing openGallery() looks like:
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
Add this statement in your onActivityResult() :
fileUri = data.getData();
so it looks:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
fileUri = data.getData(); //added this line
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Same applies to the camera intent also.
Request EXTERNAL_STORAGE permission and also run time permission if your target Android version is 6.0 or above.
EDIT:
Sorry couple of things I have not mentioned those are required are given bellow:
You may like to send the Uri instead of path this way:
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(this, UploadActivity.class);
i.setData(fileUri);
// i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
And then in UploadActivity do the following:
...
private InputStream mInputStream; // Use this stream to create bitmap and upload to server
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Receiving the data from previous activity
Intent i = getIntent();
try {
mInputStream = getContentResolver().openInputStream(i.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
...
}
...
...
private void previewMedia(boolean isImage){
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(mInputStream,null,options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
...
This works for me and hope will work on you too.
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();
}
});
I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}