I have my code below that on click opens the camera, takes a photo, gets the photo from the camera, then puts in into a imageview. However i want to take the image and apply Text (Some sort of time stamp, either the time stamp from the image preferably, or just the system datetime) on the image and save as a jpeg.
If anyone can help me out that would be awesome.
public class PhotoIntentActivity extends Activity {
private static final int ACTION_TAKE_PHOTO_B = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* NEWELY ADDED CODE */
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Bitmap replacedBitmap = timestampItAndSave(bitmap);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(replacedBitmap);
mImageView.setVisibility(View.VISIBLE);
/* NEWELY ADDED CODE */
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mImageBitmap = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO_B
}
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
*
* #param context The application's environment.
* #param action The Intent action to check for availability.
*
* #return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
}
Getting error on 4.0 emulators. Log Cat.
07-12 20:53:50.510: D/gralloc_goldfish(545): Emulator without GPU emulation detected.
07-12 20:53:54.861: W/IInputConnectionWrapper(545): showStatusIcon on inactive InputConnection
07-12 20:54:00.700: D/dalvikvm(545): GC_FOR_ALLOC freed 114K, 3% free 10052K/10311K, paused 217ms
07-12 20:54:00.710: I/dalvikvm-heap(545): Grow heap (frag case) to 11.072MB for 1228816-byte allocation
07-12 20:54:00.860: D/dalvikvm(545): GC_CONCURRENT freed 3K, 3% free 11249K/11527K, paused 4ms+3ms
07-12 20:54:00.960: D/AndroidRuntime(545): Shutting down VM
07-12 20:54:00.960: W/dalvikvm(545): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
07-12 20:54:01.000: E/AndroidRuntime(545): FATAL EXCEPTION: main
07-12 20:54:01.000: E/AndroidRuntime(545): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.android.photobyintent/com.example.android.photobyintent.PhotoIntentActivity}: java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread.deliverResults(ActivityThread.java:2976)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3019)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread.access$1100(ActivityThread.java:122)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1176)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.os.Handler.dispatchMessage(Handler.java:99)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.os.Looper.loop(Looper.java:137)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread.main(ActivityThread.java:4340)
07-12 20:54:01.000: E/AndroidRuntime(545): at java.lang.reflect.Method.invokeNative(Native Method)
07-12 20:54:01.000: E/AndroidRuntime(545): at java.lang.reflect.Method.invoke(Method.java:511)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-12 20:54:01.000: E/AndroidRuntime(545): at dalvik.system.NativeStart.main(Native Method)
07-12 20:54:01.000: E/AndroidRuntime(545): Caused by: java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor
07-12 20:54:01.000: E/AndroidRuntime(545): at android.graphics.Canvas.<init> (Canvas.java:133)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.example.android.photobyintent.PhotoIntentActivity.timestampItAndSave(PhotoIntentActivity.java:103)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.example.android.photobyinten
t.PhotoIntentActivity.setPic(PhotoIntentActivity.java:154)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.example.android.photobyintent.PhotoIntentActivity.handleBigCameraPhoto(PhotoIntentActivity.java:199)
07-12 20:54:01.000: E/AndroidRuntime(545): at com.example.android.photobyintent.PhotoIntentActivity.onActivityResult(PhotoIntentActivity.java:244)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.Activity.dispatchActivityResult(Activity.java:4649)
07-12 20:54:01.000: E/AndroidRuntime(545): at android.app.ActivityThread.deliverResults(ActivityThread.java:2972)
07-12 20:54:01.000: E/AndroidRuntime(545): ... 11 more
Updated code with draw bit map.
private Bitmap timestampItAndSave(Bitmap toEdit){
Bitmap dest = Bitmap.createBitmap(toEdit.getWidth(), toEdit.getHeight(), Bitmap.Config.ARGB_8888);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Style.FILL);
float height = tPaint.measureText("yY");
cs.drawText(dateTime, 20f, height+15f, tPaint);
cs.drawBitmap(dest,0 ,0,tPaint);
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/timestamped")));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return dest;
}
You don't want to put that in the onDraw method, as that's called whenever the View is invalidated (which you don't want).
Just create a method and put that code inside it. Call it after you've gotten the image, like so:
private Bitmap timestampItAndSave(Bitmap toEdit){
Bitmap dest = Bitmap.createBitmap(toEdit.getWidth(), toEdit.getHeight(), Bitmap.Config.ARGB_8888);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Style.FILL);
float height = tPaint.measureText("yY");
cs.drawText(dateTime, 20f, height+15f, tPaint);
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/timestamped")));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return dest;
}
I also recommend not saving it to "/sdcard/" but instead use Environment.getExternalStorageDirectory() (already implemented for you)
Edit: Also noticed you're creating a second Bitmap out of myImageBitmap; is that necessary?
Related
I want to upload images to fto using simple FTP. But it always failed to upload to FTP. The error always points to the ftp.connect. I don't know why. So I hope u can help me.
Upload.java
public class ImageUpdate extends AppCompatActivity {
private static final String TAG_ID = "id";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_IMAGE_ID = "id_image";
private static final String TAG_IMAGE_NAME= "image_name";
ProgressDialog pDialog;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String, String>> namelist, idList, imageList;
JSONArray names, names1, names2;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString = null;
Button submit;
static final String FTP_HOST = "xxxxxxxxxx";
static final String FTP_USER = "xxxxxxxxxxxx";
static final String FTP_PASS = "xxxxxxxxxxx";
String name, vid;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client2;
SessionManagement session;
String nm,addr,pos,tlp,mail,usr,pass,id,image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
session =new SessionManagement(ImageUpdate.this);
HashMap<String, String> user = session.getUserDetails();
id=user.get(SessionManagement.KEY_ID);
nm=user.get(SessionManagement.KEY_NAME);
addr=user.get(SessionManagement.KEY_ALAMAT);
mail=user.get(SessionManagement.KEY_EMAIL);
tlp=user.get(SessionManagement.KEY_TELP);
usr=user.get(SessionManagement.KEY_USERNAME);
pass=user.get(SessionManagement.KEY_PASS);
submit=(Button) findViewById(R.id.buttonUploadPicture);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imgDecodableString == null) {
Toast.makeText(ImageUpdate.this, "Choose image first, please", Toast.LENGTH_LONG);
} else {
File f = new File(imgDecodableString);
name = f.getName();
uploadFile(f);
}
}
});
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filename = cursor.getString(columnIndex);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
File f = new File("" + imgDecodableString);
f.getName();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "Pilih Bukti Transaksi",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Failed to Choose", Toast.LENGTH_LONG)
.show();
}
}
public void uploadFile(File fileName) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SimpleFTP ftp=new SimpleFTP();
try {
ftp.connect("xxxxxxx", 21, "xxxxxxxx", "xxxxxxx");
ftp.bin();
ftp.cwd("img/imageProfil/");
ftp.stor(fileName);
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
try {
ftp.disconnect();
Toast.makeText(ImageUpdate.this, "disconnect", Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(ImageUpdate.this, "failed", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.start(client2, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.end(client2, viewAction);
client2.disconnect();
}
}
stackTrace
06-20 22:32:00.692 2845-2845/com.amobi.newlomapodfix W/EGL_emulation: eglSurfaceAttrib not implemented
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: java.io.IOException: SimpleFTP received an unknown response when connecting to the FTP server: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:74)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity.uploadFile(UploadActivity.java:167)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity$1.onClick(UploadActivity.java:100)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View.performClick(View.java:4204)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View$PerformClick.run(View.java:17355)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Looper.loop(Looper.java:137)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5041)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
06-20 22:32:04.904 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
06-20 22:32:04.908 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at dalvik.system.NativeStart.main(Native Method)
This answer explains a nonconform FTP specification in simple FTP, in fact, the server should start with 220 but this library gets an exception.
(https://stackoverflow.com/a/24386510/6093353).
This tutorial implements an easy FTP upload, try to follow this
http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98
I have this code which allows users to access the camera to take photos and select images from gallery, it works on my Sony Xperia Z3 running Android 5.1.1.
I now have upgraded to a Nexus 5X running Android 6.0, but when i try to use the camera or save an image i get errors any help?
My Code to use Camera
Intent CameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
Intent SelectedCameraImage = Intent.createChooser(CameraImage, "Take A Photo With");
startActivityForResult(SelectedCameraImage, SELECTED);
My Result Handler
public void onActivityResult(int RequestCode, int ResultCode, Intent Data) {
if (ResultCode == RESULT_OK) {
if (RequestCode == SELECTED) {
Uri SelectedImageUri = Data.getData();
SelectedImagePath = getPath(SelectedImageUri);
Log.d("DatabaseOperations", "Image Path : " + SelectedImagePath);
Img.setImageURI(SelectedImageUri);
try {
FileInputStream FileInpStream = new FileInputStream(SelectedImagePath);
BufferedInputStream BufInputStream = new BufferedInputStream(FileInpStream);
DBByte = new byte[BufInputStream.available()];
BufInputStream.read(DBByte);
Log.d("DatabaseOperations", "Image Size : " + DBByte.length + " KB");
}
catch (IOException e) {
Log.d("DatabaseOperations", "Error : " + SelectedImagePath);
Log.d("DatabaseOperations", e.getMessage(), e);
}
}
}
}
public String getPath(Uri Uris) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor Cursor = managedQuery(Uris, projection, null, null, null);
int ColumnIndex = Cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Cursor.moveToFirst();
return Cursor.getString(ColumnIndex);
}
My Manifest Permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
The Errors (Logcat)
FATAL EXCEPTION: main
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: Process: rajancorporations.database, PID: 3768
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity } from ProcessRecord{c9f94d7 3768:rajancorporations.database/u0a80} (pid=3768, uid=10080) with revoked permission android.permission.CAMERA
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1620)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1573)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2658)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1507)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3930)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3890)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at rajancorporations.database.Reg$2.onClick(Reg.java:75)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View.performClick(View.java:5204)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21153)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here is my complete code for taking image from camera or Gallery and it is working fine in marshmallow with others.
Here i am Declaring Varriables
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
private static final int REQUEST_ACESS_STORAGE=3;
private static final int REQUEST_ACESS_CAMERA=2;
private Uri uri;
Here i have some Methods for permission in marshmallow
public static boolean checkPermission(String permission, Context context) {
int statusCode = ContextCompat.checkSelfPermission(context, permission);
return statusCode == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermission(AppCompatActivity activity, String[] permission, int requestCode) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission[0])) {
Toast.makeText(activity, "Application need permission", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(activity, permission, requestCode);
}
public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
fragment.requestPermissions(permission, requestCode);
}
My onclick method
if (v.getId()==R.id.idOfPhoto){
handleCamera();
}
Details of handle camera method
private void handleCamera(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
startDilog();
}else{
requestPermission(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_ACESS_STORAGE);
}
}else{
startDilog();
}
}
startdilog method
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(YourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkPermission(Manifest.permission.CAMERA,YourActivity.this)){
openCameraApplication();
}else{
requestPermission(YourActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_ACESS_CAMERA);
}
}else{
openCameraApplication();
}
}
});
myAlertDilog.show();
}
openCameraApplication method
private void openCameraApp() {
Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (picIntent.resolveActivity(getPackageManager())!= null){
startActivityForResult(picIntent, CAMERA_REQUEST);
}
}
Rest of code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST) {
if (resultCode == RESULT_OK) {
if (data != null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize =calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageview.setImageBitmap(image);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this, bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageview.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
owner_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = this.getContentResolver().query(tempUri, 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();
}
}
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==REQUEST_ACESS_STORAGE && grantResults[0]== PackageManager.PERMISSION_GRANTED){
startDilog();
}
if(requestCode==REQUEST_ACESS_CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){
openCameraApp();
}
}
it's working fine in witth all devices..
First, you assume that Data.getData() is meaningful here. There is no Uri returned by ACTION_IMAGE_CAPTURE, according to the specification. Your options are either to supply EXTRA_OUTPUT (in which case, the image should be where you indicate in that extra), or to get a thumbnail back from Data.getExtra("data"). There may be a few camera apps that do return a Uri. But there are over 8,000 Android device models, with hundreds, if not thousands, of different default camera apps. The user might also be having your request be handled by a third-party camera app. Most camera apps will give you a null value for Data.getData().
Second, even if you get a Uri, you assume that the Uri is known to the MediaStore. That is not required.
Third, even if you get a Uri and it is is known to the MediaStore, you assume that the DATA column is a path to a local file that you can access. This is not required. For example, it might be a path to removable storage, which you cannot access on Android 4.4+.
To address those three problems, use EXTRA_OUTPUT to designate where you want the camera to store the picture, and get rid of getPath() and your dependence upon the Uri.
Fourth, when working with external storage on Android 6.0+, if your targetSdkVersion is 23 or higher, you need to request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE from the user at runtime. The same holds true for the CAMERA permission.
Fifth, do not have <uses-permission> and <uses-permission-sdk-23> for the same permissions. In your case, use <uses-permission>.
Why am i getting this error??
04-27 16:09:19.823 32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823 32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823 32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 32255
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3830)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
What my application does is, opens up the camera application via an intent. Then loads the image/bitmao into an imageview. Whenever i click the save_btn button it gives me this error. Could anybody tell me why and give me a solution? Thank you.
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
private static final String TAG = "MyActivity";
Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
findViewById(R.id.captureImage).bringToFront();
findViewById(R.id.saveImage).bringToFront();
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onSaveInstanceState(Bundle outState){
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
file.delete();
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/Wiki_Camera"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="camera_wiki"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
public void save_btn(View v) {
storeImage(image);
}
}
Just guessing but it seems you store taken image only for local variable
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
While later in the code you try to store image from class variable with the same name
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
public void storeImage(Bitmap image) {
imageView.buildDrawingCache();
Bitmap bm_img = imageView.getDrawingCache();
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bm_img.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
I want to make an app that takes a picture with the device's camera, saves the image in the internal memory, and then displays that image in the next Activity. The preview works perfectly, but when I hit the Capture button the app goes to the next activity and only shows a blank white screen. Maybe I'm not writing or reading the file correctly?
Here is the Main Activity:
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "File_name";
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
//////////////////////
public void sendInfo(String pathway) {
Intent intent = new Intent(this, show_image.class);
intent.putExtra(EXTRA_MESSAGE,pathway);
startActivity(intent);
}
/////////////////
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data , Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"pic.jpg");
FileOutputStream fos = null;
if (directory == null){
Log.d("Logtag", "Error creating media file, check storage permissions: ");
return;
}
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
String path = directory.getAbsolutePath();
sendInfo(path);
} catch (FileNotFoundException e) {
Log.d("Logtag", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Logtag", "Error accessing file: " + e.getMessage());
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A safe way to get an instance of the Camera object.
*/
public Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
Toast.makeText(getApplicationContext(), "Camera is not available (in use or does not exist)",
Toast.LENGTH_LONG).show();
}
return c; // returns null if camera is unavailable
}
}
Here is the Second activity that is supposed to display the image that was just taken:
public class show_image extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String path = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
try {
File f = new File(path, "pic.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img= new ImageView(this);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static Bitmap decodeFile(File f, final int maxSize) {
Bitmap b = null;
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > maxSize || o.outWidth > maxSize) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
} catch (Exception e) {
Log.e("Logtag", "Error processing bitmap", e);
} finally {
//FileUtil.closeQuietly(fis);
}
return b;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The LogCat from Android Studio:
02-25 12:32:49.389 17041-17041/edu.ramapo.camer I/System.out﹕ debugger has settled (1496)
02-25 12:32:49.620 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
02-25 12:32:49.620 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11360: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
02-25 12:32:49.620 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 12:32:49.620 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
02-25 12:32:49.620 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11366: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
02-25 12:32:49.620 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 12:32:49.630 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
02-25 12:32:49.630 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 9050: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
02-25 12:32:49.630 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
02-25 12:32:49.660 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method
android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
02-25 12:32:49.660 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 367: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
02-25 12:32:49.660 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 12:32:49.670 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
02-25 12:32:49.670 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 389: Landroid/content/res/TypedArray;.getType (I)I
02-25 12:32:49.670 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 12:32:50.611 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libEGL_adreno200.so
02-25 12:32:50.621 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-25 12:32:50.621 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv2_adreno200.so
02-25 12:32:50.631 17041-17041/edu.ramapo.camer I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM build: HAREESHG_Nondeterministic_AU+PATCH[ES]_msm8960_JB_1.9.6_MR2_CL3219408_release_ENGG (CL3219408)
Build Date: 09/28/13 Sat
Local Branch: hhh
Remote Branch: quic/jb_1.9.6_1
Local Patches: 8d50ec23e42ef52b570aa6ff1650afac0b503d78 CL3219408: Fix in the Glreadpixels for negative offsets and larger dimensions.
801859126f6ca69482b39a34ca61447e3f7cded8 rb: fix panel settings to clear undrawn/undefined buffers
Reconstruct Branch: LOCAL_PATCH[ES]
02-25 12:32:50.991 17041-17041/edu.ramapo.camer D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 12:32:51.552 17041-17041/edu.ramapo.camer I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-25 12:32:56.037 17041-17047/edu.ramapo.camer D/dalvikvm﹕ Debugger has detached; object registry had 4113 entries
02-25 12:33:18.651 17041-17041/edu.ramapo.camer D/dalvikvm﹕ GC_FOR_ALLOC freed 694K, 38% free 12155K/19420K, paused 29ms, total 32ms
02-25 12:33:18.771 17041-17041/edu.ramapo.camer I/dalvikvm-heap﹕ Grow heap (frag case) to 45.705MB for 31961104-byte allocation
02-25 12:33:24.507 17041-17041/edu.ramapo.camer D/dalvikvm﹕ GC_FOR_ALLOC freed 31627K, 40% free 11825K/19424K, paused 30ms, total 30ms
02-25 12:33:24.587 17041-17041/edu.ramapo.camer I/dalvikvm-heap﹕ Grow heap (frag case) to 45.382MB for 31961104-byte allocation
Well right now I made a copy of the app I sent you the link already here is the code:
public class GlassARTest extends FragmentActivity {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
private Camera mCamera;
private CameraPreview mPreview;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mContext = this;
if(checkCameraHardware(mContext)){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
return pictureFile.getPath();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
Intent intent = new Intent(mContext, ImageDisplayActivity.class);
intent.putExtra(ImageDisplayActivity.KEY_PATH, result);
startActivity(intent);
}
}
}.execute();
}
};
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create 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 {
return null;
}
return mediaFile;
}
} private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create 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 {
return null;
}
return mediaFile;
}
}
and the other Activity:
public class ImageDisplayActivity extends FragmentActivity{
public static final String KEY_PATH = "path";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
final ImageView imageDisplay = (ImageView)findViewById(R.id.image_displayer);
final Bundle extras = getIntent().getExtras();
if(extras != null){
final String path = extras.getString(KEY_PATH);
File imgFile = new File(path);
Bitmap bitmap = decodeFile(imgFile);
imageDisplay.setImageBitmap(bitmap);
}
}
private Bitmap decodeFile(File f){
Bitmap b = null;
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > 50 || o.outWidth > 50) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(50 / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
}
return b;
}
}
this code worked showing a pixelated image of what I took picture of (as I'm just decoding it in low quality for testing purposes).
I hope this help you.
I have been following this tutorial: AndroidHive - working with Camera API to try and enable taking photos in my app. However, I'm getting an error once I press my "take photo button".
LogCat:
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/Dob_in_a_Hoon_photos﹕ Failed to create Dob_in_a_Hoon_photos directory
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/AndroidRuntime﹕ Shutting down VM
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40e21438)
09-16 11:04:00.559 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:441)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.getOutputMediaFileUri(dob_in_a_hoon.java:97)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.captureImage(dob_in_a_hoon.java:89)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.access$000(dob_in_a_hoon.java:28)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon$1.onClick(dob_in_a_hoon.java:60)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4963)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
09-16 11:04:10.529 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour I/Process﹕ Sending signal. PID: 19561 SIG: 9
Here is my .java file:
public class dob_in_a_hoon extends ActionBarActivity {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Dob_in_a_Hoon_photos";
private Uri fileUri;
private ImageView Hoon_Image;
private Button button_take_photo;
private String driver_spinner_array[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dob_in_a_hoon);
driver_spinner_array = new String[2];
driver_spinner_array[0] = "Yes";
driver_spinner_array[1] = "No";
Spinner Driver_spinner = (Spinner) findViewById(R.id.driver_selector);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, driver_spinner_array);
Driver_spinner.setAdapter(adapter);
Hoon_Image = (ImageView) findViewById(R.id.CapturedImage);
button_take_photo = (Button)findViewById(R.id.btn_take_photo);
button_take_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dob_in_a_hoon, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void captureImage(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d(IMAGE_DIRECTORY_NAME, "Failed to create " + IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
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 {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
if (resultCode==RESULT_OK){
previewCapturedImage();
}else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"User Cancelled image Capture", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
private void previewCapturedImage(){
try{
Hoon_Image.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
Hoon_Image.setImageBitmap(bitmap);
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super .onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
}
Can anybody see where I am going wrong in my code, and what I have to do to fix it?
I created a sample snippet and tested out the mkdirs as shown in your code, it causes similar exception if i removed the permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Can you please check your manifest to make sure you have these defined.
If above is not the problem, another (unlikely) source of error could be your SD card is running out of space or some permissions restrictions. In this case, i would try the app on android emulator or another device.
This should be added in Manifest to use camera feature:
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>