This class call the camera class which click the photo but on activity result of this class it gives error on line 41.
package com.example.fish;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import com.non_activity.*;
public class Camera extends Activity
{
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//setContentView(R.layout.name_image);
image=(ImageView)findViewById(R.id.cameraImage);
Intent in= new Intent(this,com.camera.CameraCall.class);
startActivityForResult(in, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1)
{
ImageRotation ri= new ImageRotation();
image.setImageBitmap(ri.getImageOrientation(com.camera.Camera_nonClass.getPath(), 7)); //line 41
}
}
}
This is the actual camera code application which actually clicks the photo from camera
and return the result back to the calling camra class.
package com.camera;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class CameraCall extends Activity
{
final private int CAPTURE_IMAGE = 1;
String imgPath=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
cameraCheck();
}
private void cameraCheck()
{
Context context=CameraCall.this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
//yes
captureImage();
}else{
//no
finish();
}
}
/******************************************** Camera Function Implementation*******************************************/
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage()
{
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
public Uri setImageUri()
{
File mediaFile=null;
File mediaStorageDir = new File("/sdcard/Fish/");
if (mediaStorageDir.exists()==false)
{
Boolean b=mediaStorageDir.mkdirs();
if(b==false)
return null;
}
if(mediaStorageDir.exists()==true)
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".PNG");
}
Uri imgUri = Uri.fromFile(mediaFile);
this.imgPath = mediaFile.getAbsolutePath();
com.camera.Camera_nonClass.setPath(this.imgPath);
Log.e("image path 1122:-", this.imgPath+"");
return imgUri;
}
public String getImagePath()
{
return imgPath;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != Activity.RESULT_CANCELED)
{
if (requestCode == CAPTURE_IMAGE)
{
com.camera.Camera_nonClass.setPath(getImagePath());
Log.e("image path 11:-",com.camera.Camera_nonClass.getPath()+"");
finish();
}
{
super.onActivityResult(requestCode, resultCode, data);
}
}
}
}
This is the file which store the path of image taken from camra.
package com.camera;
public class Camera_nonClass
{
static String path;
public static String getPath() {
return path;
}
public static void setPath(String path) {
Camera_nonClass.path = path;
}
}
Related
I am facing an issue which I do not understand. I am taking a picture then creating a PNG image file as per code that follows but somewhere down the line a random string is being added to the filename which causes me all sorts of issues. For example (as per tutorials I have found): I create an image called dimage_(generated timestamp) and save the string to shared preferences and the image in getExternalFilesDir(Environment.DIRECTORY_PICTURES). In shared preferences the string is correct but the file has the above mentioned string appended.
Eg:
The generated filename string saved in shared prefs:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="driver_picture">dimage_20190610_065509</string>
</map>
Whereas the file checked with adb results as:
127|generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files/Pictures $ ls
dimage_20190610_0655091215099619.png
generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files /Pictures $
I have no clue where the 1215099619 extra part comes from!
This is the code of the activity:
package africa.mykagovehicledrivers;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class RegisterDriverImage extends AppCompatActivity {
String currentPhotoPath;
final int REQUEST_TAKE_PHOTO = 1;
final int CAMERA_PERMISSIONS = 3;
Activity activity = this;
ImageView imgTakePicture, imgDriver;
Button btnContinueDriver;
ProgressBar prgImage;
SharedPreferences prefs;
SharedPreferences.Editor edit;
String imageFileName;
Tools t;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.setUcropOptions(activity);
UCrop.of(starturi, destinationuri).withOptions(options).start(activity);
}
// On result from cropper add to image view
if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
prgImage.setVisibility(View.VISIBLE);
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgDriver, new Callback() {
#Override
public void onSuccess() {
Log.d("-------->", "onSuccess: CROPPED!");
prgImage.setVisibility(View.INVISIBLE);
btnContinueDriver.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_driver_image);
prefs = getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
edit = prefs.edit();
imgTakePicture = findViewById(R.id.imgTakePicture);
imgDriver = findViewById(R.id.imgDriver);
btnContinueDriver = findViewById(R.id.btnContinueDriver);
prgImage = findViewById(R.id.prgImage);
t = new Tools(getApplication(), getApplicationContext(), this);
imgTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnContinueDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString("driver_picture", imageFileName);
edit.putString("nextstep", "drivinglicense");
edit.apply();
Intent drivinglicense = new Intent(getApplicationContext(), RegisterDrivingLicense.class);
startActivity(drivinglicense);
finish();
}
});
// Always ask for camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA }, CAMERA_PERMISSIONS);
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION FAILED", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"africa.mykagovehicledrivers.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
imageFileName = "dimage_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
As per code I am using String imageFileName; to save the path and then use it in the button click action to save it into shared preferences.
Thanks!
Found out the reasin. createTempFile does this. Switched to new File() and this solved the issue.
MainActivity.java :
package com.example.dell.capcrop;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
final int CAMERA_CAPTURE=1;
private Uri picUri;
final int PIC_CROP=2;
Bundle bundle;
Bitmap bitmap;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn=(Button)findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId()==R.id.capture_btn){
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent,CAMERA_CAPTURE);
}
catch (ActivityNotFoundException anfe){
String errorMessage ="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri,"image/*");
cropIntent.putExtra("crop","true");
cropIntent.putExtra("aspectX",1);
cropIntent.putExtra("aspectY",1);
cropIntent.putExtra("outputX",256);
cropIntent.putExtra("outputY",256);
cropIntent.putExtra("return_data",true);
startActivityForResult(cropIntent,PIC_CROP);
}
catch (ActivityNotFoundException anfe)
{
String errorMessage="Whoops - your device doesn't support capturing image";
Toast toast=Toast.makeText(this,errorMessage,Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request&&resultCode==RESULT_OK)
{
bundle=data.getExtras();
bitmap=(Bitmap)bundle.get("data");
img.setImageBitmap(bitmap);
Thread thread=new Thread()
{
#Override
public void run() {
try {
sleep(2000);
Intent intent=new Intent(getApplicationContext(),result.class);
bundle.putParcelable("bmp",bitmap);
intent.putExtras(bundle);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
picUri = data.getData();
performCrop();
} else if (requestCode == PIC_CROP) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
}
My app is basically a sign language interpreter and I need to remove an error. Here is the code in which there is multiple onactivityresult() definition which is causing error. I do some changes but all in vain. In this code the mobile camera capture image and show a frame in which the user crop the required part of image and show in the next activity.
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import cafe.adriel.androidaudiorecorder.AndroidAudioRecorder;
import cafe.adriel.androidaudiorecorder.Util;
import cafe.adriel.androidaudiorecorder.example.R;
public class MainActivity extends AppCompatActivity
{
public static final String EXTRA_FILE_PATH = "filePath";
public static final String EXTRA_COLOR = "color";
static Date createdTime= new Date();
public static final String AUDIO_FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + createdTime + "_rec.wav";
public static final int RECORD_AUDIO = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(getResources().getColor(R.color.colorPrimaryDark)));
}
Util.requestPermission(this, Manifest.permission.RECORD_AUDIO);
Util.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RECORD_AUDIO) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Audio recorded successfully!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Audio was not recorded", Toast.LENGTH_SHORT).show();
}
}
}
public void recordAudio(View v) {
AndroidAudioRecorder.with(this)
.setFilePath(AUDIO_FILE_PATH)
.setColor(getResources().getColor(R.color.recorder_bg))
.setRequestCode(RECORD_AUDIO)
.record();
}
}
Consider using one Android's default external storage folders, in your case the DIRECTORY_MUSIC like this
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
You can use this File class constructor to create a new folder on the SD card:
File audioFolder = new File(Environment.getExternalStorageDirectory(),
"newaudiofolder")
if (!audioFolder.exists()) {
boolean success = audioFolder.mkdir()
if (success) {
// save the file
}
}
When I take a picture, the picture will saved on the SD.(This works very well)
But the picture won´t shows in the imageView. Do you have any idea?
package de.example.Camera;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Cam extends Activity {
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_cam);
Button button2 = (Button) findViewById(R.id.photo);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start ActivityTwo
/*
* Intent intent = new Intent(getApplicationContext(),
* ActivityTwo.class); intent.putExtra("MyStringValue",
* editText1.getText().toString()); startActivity(intent);
*/
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
}else {
// The picture was returned
Bundle extras = intent.getExtras();
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
private Uri getOutputMediaFile() throws IOException {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DayTwentyNine");
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
if (mediaFile.exists() == false) {
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
}
return Uri.fromFile(mediaFile);
}
}
In the manifest I have are the following:
uses-feature android:name="android.hardware.camera" android:required="false"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here I have this peace of code that works fine the first function open the camera and take the picture and the second one place the image you took into an image view...
public void takePictu(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
photo3 = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo3);
imageView.buildDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo3.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
}
My app is to open the built in camera and save it into sd card then start a new activity and preview the captured image on it.
This is the loginActivity that start a new AsynTask to open the camera :
package com.android.grad;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.Camera.R;
public class LoginActivity extends Activity {
private final int MEDIA_TYPE_IMAGE = 1;
private CheckBox rememberMe;
private EditText userName, passWord;
private Button loginBtn;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String path;
private Uri fileUri;
private OnClickListener loginOnClick = new OnClickListener() {
public void onClick(View v) {
new LoginTask(LoginActivity.this, fileUri).execute();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
path = fileUri.getPath();
loginBtn = (Button) findViewById(R.id.signInBtn);
loginBtn.setOnClickListener(loginOnClick);
rememberMe = (CheckBox) findViewById(R.id.keepMe);
userName = (EditText) findViewById(R.id.userNameID);
passWord = (EditText) findViewById(R.id.passwordID);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
try {
userName.setText(sp.getString("username", ""));
passWord.setText(sp.getString("password", ""));
rememberMe.setChecked(sp.getBoolean("rememberMe", false));
} catch (ClassCastException ex) {
}
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
Editor editor = sp.edit();
if (rememberMe.isChecked()) {
editor.putString("username", userName.getText().toString());
editor.putString("password", passWord.getText().toString());
} else {
editor.putString("username", "");
editor.putString("password", "");
}
editor.putBoolean("rememberMe", rememberMe.isChecked());
editor.commit();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(LoginActivity.this,
PreviewActivity.class);
intent.putExtra("path", path);
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
Toast.makeText(getApplicationContext(),
"User cancelled the image capture", Toast.LENGTH_LONG)
.show();
} else {
// Image capture failed, advise user
}
}
}
/** Create a file Uri for saving an image or video */
private Uri getOutputMediaFileUri(int type) {
File f = getOutputMediaFile(type);
if (f == null) {
Toast.makeText(LoginActivity.this, "MyCameraApp File not found",
Toast.LENGTH_LONG);
return null;
}
return Uri.fromFile(f);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
// Check if SD card is mounted
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File externalFilesDir = LoginActivity.this
.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File outFile = new File(externalFilesDir, "IDOCR");
if (!outFile.exists())
outFile.mkdirs();
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String path = outFile.getPath() + File.separator + "IMG"
+ timeStamp + ".jpg";
File mediaFile = new File(path);
return mediaFile;
}
Toast.makeText(LoginActivity.this, "SD card unmounted",
Toast.LENGTH_LONG);
return null;
}
}
And this is the AsynTask :-
package com.android.grad;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
public class LoginTask extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
private ProgressDialog pd;
private Uri fileUri;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
public LoginTask(Activity activity, Uri fileUri) {
this.activity = activity;
this.fileUri = fileUri;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(activity, "Signing in",
"Please wait while we are signing you in..");
}
#Override
protected Boolean doInBackground(Void... arg0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
pd = null;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
activity.startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
and this is the previewActivity:-
package com.android.grad;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.Camera.R;
import com.OCR.ID.AndroidImage;
import com.OCR.ID.Segement;
public class PreviewActivity extends Activity {
private ImageView previewIV;
private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String path;
private boolean crop = true;
private boolean resample = true;
private ProgressDialog pd;
OnClickListener processOnClickListener = new OnClickListener() {
public void onClick(View v) {
try {
createProgressDialog();
pd.show();
new Segement(PreviewActivity.this, pd).execute(path);
} catch (IOException e) {
}
}
};
private void createProgressDialog() {
pd = new ProgressDialog(PreviewActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setTitle("Extract ID");
pd.setMessage("Processing...");
pd.setIcon(R.drawable.ic_launcher);
pd.setProgress(0);
pd.setCancelable(false);
}
private OnClickListener backOnClickListener = new OnClickListener() {
public void onClick(View v) {
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(path))),
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
previewIV.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
path = getIntent().getExtras().getString("path");
previewIV = (ImageView) findViewById(R.id.previewPicID);
previewIV.setImageBitmap(AndroidImage.decodeSampledBitmapFromSDcard(
path, 150, 150));
// previewIV.setImageBitmap(AndroidImage.readImage(path));
Button process = (Button) findViewById(R.id.processID);
process.setOnClickListener(processOnClickListener);
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(backOnClickListener);
}
}
The error that appear that sometimes when take picture it appear in the previewActivity and
sometime doesn't appear ?
Why that error
??