I am trying to save a video from VideoView to the SD card, by touching the VideoView. No errors in LogCat, but my Toast I set up says "Error during video saving", which tells me my boolean I set up did not get to the part where it's set to true. It must be in the file I/O part. One part that works though, is a directory does get created, but the file itself is not found in the directory, it's empty.
Any mistakes anyone sees?
I will post my two main methods that are important, then below I'll post the whole class.
UPDATE: Here is my working code (changed a couple lines in the saveVideo method.)
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
boolean success = false;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(vidDir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
My old, unworking saveVideo() method.
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
String sourceVideoName = uriVideo.getPath();
boolean success = false;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
fileVideo = new File(vidDir.getPath(), videoName);
try {
bis = new BufferedInputStream(new FileInputStream(sourceVideoName));
bos = new BufferedOutputStream(new FileOutputStream(fileVideo, false));
byte[] buf = new byte[8192];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != 0);
success = true;
} catch (IOException e) {
}finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
My dispatchTakeVideoIntent() method. I commented out some code that might be needed... I kept getting a null pointer though on fileUri line (was it from fileUri or fileVideo?), so not sure why.
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// // set name of video
// Uri fileUri = Uri.fromFile(fileVideo);
// takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
MakePhotoVideo.java
package org.azurespot.makecute;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import org.azurespot.R;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MakePhotoVideo extends ActionBarActivity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final int ACTION_TAKE_VIDEO = 2;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
File fileVideo;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private PhotoStorageDirFactory mPhotoStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
mVideoView = (VideoView) findViewById(R.id.video_view);
mVideoView.setVisibility(View.INVISIBLE);
mImageBitmap = null;
mVideoUri = null;
Button photoBtn = (Button) findViewById(R.id.click);
setBtnListenerOrDisable(
photoBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
Button videoBtn = (Button) findViewById(R.id.record_video);
setBtnListenerOrDisable(
videoBtn,
mTakeVidOnClickListener,
MediaStore.ACTION_VIDEO_CAPTURE
);
mPhotoStorageDirFactory = new BasePhotoDirFactory();
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mPhotoStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("Camera", "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;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
bitmap = rotateBitmap(bitmap, 90);
savePhoto(bitmap);
/* Associate the Bitmap to the ImageView, make sure the VideoView
* is cleared to replace with ImageView */
mImageView.setImageBitmap(bitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
// save your photo to SD card
private void savePhoto(final Bitmap bitmapPhoto){
// set OnClickListener to save the photo
mImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean success = false;
File photoDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + "/Saved iCute Photos");
photoDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String photoName = "Image_"+ n +".jpg";
File filePhoto = new File (photoDir, photoName);
// if (filePhoto.exists ()) filePhoto.delete ();
try {
FileOutputStream out = new FileOutputStream(filePhoto);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
});
}
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
String sourceVideoName = uriVideo.getPath();
boolean success = false;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
fileVideo = new File(vidDir.getPath(), videoName);
try {
bis = new BufferedInputStream(new FileInputStream(sourceVideoName));
bos = new BufferedOutputStream(new FileOutputStream(fileVideo, false));
byte[] buf = new byte[8192];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != 0);
success = true;
} catch (IOException e) {
}finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
public Bitmap rotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.set(matrix);
matrix.setRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
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:
File f;
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);
}
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// // set name of video
// Uri fileUri = Uri.fromFile(fileVideo);
// takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
private void handleCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
// Post recorded video into VideoView
private void handleCameraVideo(Intent intent) {
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
mVideoView.start();
saveVideo(mVideoUri);
Log.d("VIDEO INTENT: ", "END OF METHOD");
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
};
Button.OnClickListener mTakeVidOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakeVideoIntent();
}
};
// Intent data is how the photo and video transfer into their views
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO
case ACTION_TAKE_VIDEO: {
if (resultCode == RESULT_OK) {
handleCameraVideo(data);
}
break;
} // ACTION_TAKE_VIDEO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_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);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Makes the UP caret go back to the previous fragment MakeCuteFragment
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Just update the lines in dispatchTakeVideoIntent()
provide a proper path to create fileVideo first and make sure to call createNewFile() before putting in intent.
Related
I have not found anything online that addresses this particular issue. I have an activity that takes a photo or video using the Android camera app. It then returns from the camera with the image or video, and shows it in a view. Both my video and image, capture and show, work fine when I am in the same configuration. But if I start the camera from my app in say, portrait, then when I am in the camera app I decide to change it to landscape, then once I come back from the camera app, my image shows a blank ImageView. It works fine if I stay in the same configuration. Like when I start in portrait, and use the camera app also in portrait, then my ImageView shows the image upon returning. Since I cannot write code for the camera app, not sure how to handle this.
However, my video has no trouble if I change orientation during use of the camera video. It displays fine when it comes back into my app, no matter which orientation I am in in either the app or the camera app.
But why does the image have problems? I've tried to save state in onSaveInstanceState and onRestoreInstanceState, but this does not affect anything. I get null values for all my variables in those methods, when I log them (for video too). I think because it might have more to do with my Intent data? But that's just a guess. I looked over the Intent and see nothing missing. The image intent is a little different from the video intent, so maybe I'm missing something.
I do have 2 different xml files for the portrait and landscape layout, but they are identical and in the right folders. Android auto-chooses them when I do a configuration change.
If anyone has tips, thanks very much.
UPDATE:
I tried to add a line of code in my manifest: android:configChanges="keyboardHidden|orientation|screenSize"
and I overrode onConfigurationChanged(), but now my image comes back as a black screen. Both layout files are in my layout folder.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_make_photo_video_land);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.activity_make_photo_video);
}
}
UPDATE 2:
I undid everything I tried in UPDATE 1. Since that gave me a black screen and other unfixable bugs.
This time, I have added a configuration selector in onCreate to manually change the view:
// Checks the orientation of the screen
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_make_photo_video_land);
mImageView = (ImageView) findViewById(R.id.taken_photo_land);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
}
After more logging, I have realized when I change the configuration in the camera app, the following methods execute in this order (listed from 1st activity start):
onCreate()
onSavedInstanceState() - I leave my app to go to the camera
onCreate() - I return from app with a photo, a log on mImageBitmap is null.
onRestoreInstanceState()
inActivityResult() - then it processes the photo that is captured from camera.
The only thing I persist in onSavedInstanceState() is the mCurrentPhotoPath, which is needed to run the setPic() method in inActivityResult().
In onSavedInstanceState():
outState.putString("FILE_PATH", mCurrentPhotoPath);
In onCreate():
if (savedInstanceState != null) {
mCurrentPhotoPath = savedInstanceState.getString("FILE_PATH");
}
This processes fine, and a log on the bitmap value is not null. So why doesn't the image post still??
MakePhotoVideo.java
package org.azurespot.makecute;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.azurespot.R;
import org.azurespot.cutecollection.CuteCollection;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MakePhotoVideo extends ActionBarActivity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final int ACTION_TAKE_VIDEO = 2;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private File fileVideo;
private String mCurrentPhotoPath;
String videoPath;
private int position = 0;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private PhotoStorageDirFactory mPhotoStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
mVideoView = (VideoView) findViewById(R.id.video_view);
mVideoView.setVisibility(View.INVISIBLE);
mImageView.setSaveEnabled(true);
Button photoBtn = (Button) findViewById(R.id.click);
setBtnListenerOrDisable(photoBtn, mTakePicOnClickListener, MediaStore.ACTION_IMAGE_CAPTURE);
Button videoBtn = (Button) findViewById(R.id.record_video);
setBtnListenerOrDisable(videoBtn,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
mPhotoStorageDirFactory = new BasePhotoDirFactory();
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void viewCollection(View v){
// finishes/restarts the activity so the unsaved video does not corrupt
Intent intent = getIntent();
finish();
startActivity(intent);
// goes to Cute Collection activity
Intent i = new Intent(this, CuteCollection.class);
startActivity(i);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mPhotoStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("Camera", "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;
/* Decode the JPEG file into a Bitmap */
mImageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
mImageBitmap = rotateBitmap(mImageBitmap, 90);
}
savePhoto(mImageBitmap);
/* Associate the Bitmap to the ImageView, make sure the VideoView
* is cleared to replace with ImageView */
mImageView.setImageBitmap(mImageBitmap);
Log.d("TAG", "Value of mImageBitmap inside setPic(): " + mImageBitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
// save your photo to SD card
private void savePhoto(final Bitmap bitmapPhoto){
// set OnClickListener to save the photo
mImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean success = false;
File photoDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + "/Cute Photos");
photoDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String photoName = "Photo"+ n +".jpg";
File filePhoto = new File (photoDir, photoName);
// if (filePhoto.exists ()) filePhoto.delete ();
try {
FileOutputStream out = new FileOutputStream(filePhoto);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute photo saved!",
Toast.LENGTH_LONG);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_SHORT).show();
}
}
});
}
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
boolean success = false;
if(event.getAction() == MotionEvent.ACTION_UP) {
try {
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Cute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video" + n + ".mp4";
fileVideo = new File(vidDir.getAbsolutePath(), videoName);
videoPath = fileVideo.getAbsolutePath();
Log.d("TAG", "Value of videoPath:" + videoPath);
fileVideo.setWritable(true, false);
OutputStream out = new FileOutputStream(fileVideo);
InputStream in = getContentResolver().openInputStream(uriVideo);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.close();
in.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute video saved!",
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_SHORT).show();
}
}
return true;
}
});
}
public Bitmap rotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.set(matrix);
matrix.setRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
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:
File f;
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);
}
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
private void handleCameraPhoto() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
Log.d("TAG", "Value of mCurrentPhotoPath: " + mCurrentPhotoPath);
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
// Post recorded video into VideoView
private Uri handleCameraVideo(Intent intent) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
// mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
mVideoView.start();
// saves video to file
saveVideo(mVideoUri);
return mVideoUri;
}
// click listener for the Android Camera button (not my app's button)
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
// mImageBitmap = null;
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
Button.OnClickListener mTakeVidOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakeVideoIntent();
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
// Intent data is how the photo and video transfer into their views
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleCameraPhoto();
} else {
Log.d("TAG", "Result of photo not work.");
}
break;
} // ACTION_TAKE_PHOTO
case ACTION_TAKE_VIDEO: {
if (resultCode == RESULT_OK) {
handleCameraVideo(data);
}
break;
} // ACTION_TAKE_VIDEO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
outState.putString("FILE_PATH", mCurrentPhotoPath);
if (mVideoUri != null) {
// use onSaveInstanceState in order to store the video or photo
outState.putInt("PositionVideo", mVideoView.getCurrentPosition());
// playback position for orientation change
mVideoView.pause();
}
// super should be last in this method
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mCurrentPhotoPath = savedInstanceState.getString("FILE_PATH");
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
if (mVideoUri != null) {
// for video, restores position it was playing
position = savedInstanceState.getInt("PositionVideo");
mVideoView.seekTo(position);
}
super.onRestoreInstanceState(savedInstanceState);
}
/**
* 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.setClickable(false);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Makes the UP caret go back to the previous fragment MakeCuteFragment
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
After all of my trial and error, I finally found the problem. My 2nd update was very close, the only fault was in the
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
method. I had this in onCreate, only executed if it passed the null check, but what I forgot is that the image bitmap does come back null when the configuration changes in the camera app, so the visibility will always be set to invisible. The IMAGEVIEW_VISIBILITY_STORAGE_KEY was set up to be true if the bitmap is not null, and false if it is null. So once I got rid of this, my other saving state code worked really well. Below is the final working code.
MakePhotoVideo.java
package org.azurespot.makecute;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.azurespot.R;
import org.azurespot.cutecollection.CuteCollection;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MakePhotoVideo extends ActionBarActivity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final int ACTION_TAKE_VIDEO = 2;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private File fileVideo;
private String mCurrentPhotoPath;
String videoPath;
private int position = 0;
int targetH;
int targetW;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private PhotoStorageDirFactory mPhotoStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
mVideoView = (VideoView) findViewById(R.id.video_view);
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
mImageView.setSaveEnabled(true);
Button photoBtn = (Button) findViewById(R.id.click);
setBtnListenerOrDisable(photoBtn, mTakePicOnClickListener, MediaStore.ACTION_IMAGE_CAPTURE);
Button videoBtn = (Button) findViewById(R.id.record_video);
setBtnListenerOrDisable(videoBtn, mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
mPhotoStorageDirFactory = new BasePhotoDirFactory();
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void viewCollection(View v){
// finishes/restarts the activity so the unsaved video does not corrupt
Intent intent = getIntent();
finish();
startActivity(intent);
// goes to Cute Collection activity
Intent i = new Intent(this, CuteCollection.class);
startActivity(i);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mPhotoStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("Camera", "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() {
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
/* 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 image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
targetH = 570;
targetW = 960;
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
targetH = 960;
targetW = 570;
}
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inBitmap = mImageBitmap;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
mImageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
mImageBitmap = rotateBitmap(mImageBitmap, 90);
}
savePhoto(mImageBitmap);
/* Associate the Bitmap to the ImageView, make sure the VideoView
* is cleared to replace with ImageView */
mImageView.setImageBitmap(mImageBitmap);
mVideoUri = null;
}
// save your photo to SD card
private void savePhoto(final Bitmap bitmapPhoto){
// set OnClickListener to save the photo
mImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean success = false;
File photoDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + "/Cute Photos");
photoDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String photoName = "Photo"+ n +".jpg";
File filePhoto = new File (photoDir, photoName);
try {
FileOutputStream out = new FileOutputStream(filePhoto);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute photo saved!",
Toast.LENGTH_LONG);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_SHORT).show();
}
}
});
}
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
boolean success = false;
if(event.getAction() == MotionEvent.ACTION_UP) {
try {
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Cute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video" + n + ".mp4";
fileVideo = new File(vidDir.getAbsolutePath(), videoName);
videoPath = fileVideo.getAbsolutePath();
Log.d("TAG", "Value of videoPath:" + videoPath);
fileVideo.setWritable(true, false);
OutputStream out = new FileOutputStream(fileVideo);
InputStream in = getContentResolver().openInputStream(uriVideo);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.close();
in.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute video saved!",
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_SHORT).show();
}
}
return true;
}
});
}
public Bitmap rotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.set(matrix);
matrix.setRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
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:
File f;
try {
f = setUpPhotoFile();
Log.d("TAG", "Value of f in picture intent: " + f);
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);
}
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
private void handleCameraPhoto() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
// Post recorded video into VideoView
private Uri handleCameraVideo(Intent intent) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
mVideoView.start();
// saves video to file
saveVideo(mVideoUri);
return mVideoUri;
}
// click listener for the Android Camera button (not my app's button)
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
// mImageBitmap = null;
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
Button.OnClickListener mTakeVidOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakeVideoIntent();
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
// Intent data is how the photo and video transfer into their views
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleCameraPhoto();
}
break;
}
case ACTION_TAKE_VIDEO: {
if (resultCode == RESULT_OK) {
handleCameraVideo(data);
}
break;
}
}
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
outState.putString("FILE_PATH", mCurrentPhotoPath);
if (mVideoUri != null) {
// use onSaveInstanceState in order to store the video or photo
outState.putInt("PositionVideo", mVideoView.getCurrentPosition());
// playback position for orientation change
mVideoView.pause();
}
// super should be last in this method
super.onSaveInstanceState(outState);
}
// this is called after onCreate (when returning from camera app),
// so br careful what you put here
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mCurrentPhotoPath = savedInstanceState.getString("FILE_PATH");
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
if (mVideoUri != null) {
// for video, restores position it was playing
position = savedInstanceState.getInt("PositionVideo");
mVideoView.seekTo(position);
}
super.onRestoreInstanceState(savedInstanceState);
}
/**
* 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.setClickable(false);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Makes the UP caret go back to the previous fragment MakeCuteFragment
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Hi We have the same problem in our one of the product, We apply the below solution it's work fine, actually our client has the Samsung device. Let's open your android manifest file see the MakePhotoVideo activity. see below what you have to add inside your activity tag.
<activity android:name=".MakePhotoVideo "
android:label="#string/app_name" android:configChanges="keyboardHidden|orientation">
Actually there are lots of use case related to camera intent, especially Samsung device has majority of problem due to of the customization the native application, Apply this attribute to your activity tag. Let me know if you have any problem. thank you.
Whatever happens in the camera app while it is fulfilling your intent, causes the system to destroy your activity because it needs more memory.
You need to override onSaveInstanceState(Bundle savedInstanceState) and save the ImageView state, and maybe other values, too. See an answer to Saving Activity state in Android for details.
You should be careful restoring app state when the activity is created to answer its startActivityForResult(), as explained here.
try to recieve the bitmap in onSaveInstanceState():
mCurrentPhotoPath = savedInstanceState.getString("FILE_PATH");
mImageBitmap = savedInstanceState.getParceable("BITMAP_STORAGE_KEY");
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
I'm having a configuration problem with my ImageView. I found code online that helps me to integrate taking a photo from my app. What it does is leaves the app, goes to the Android Camera, then returns with the photo. From here, I place it into an ImageView. Everything worked fine until I had to add a configuration change. The image disappears when I change the configuration.
To overcome this problem, I managed a way to get my VideoView (it alternates the view with my ImageView) to save state, but it has different code requirements to save than the image does. Here is what I have so far. I have tried to research solutions, but nothing makes sense to me. Does my code look incomplete?
Thanks.
UPDATE:
Upon further study, the state is saved if I do not rotate the camera while taking a photo. If the starting orientation is the same as the orientation when I come back to the app (after taking photo), then the configuration change within the app works fine. The problem is that if I, say, start in portrait mode, then click the photo button. This takes me to the Android camera. Then I decide I want a landscape photo after all, so I rotate it then snap the photo. I press okay, which then takes me back to the app. Once I arrive, since I'm now in landscape mode, my ImageView is blank.
Also: I did a log on the mImageBitmap inside of onSaveInstanceState & onRestoreInstanceState and they both are null. But why? Maybe because the bitmap is not created until it comes back from the camera? Then how am I supposed to save it on a configuration change? So confused.
My two saving state methods:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
if (mVideoUri != null) {
// use onSaveInstanceState in order to store the video or photo
outState.putInt("PositionVideo", mVideoView.getCurrentPosition());
// playback position for orientation change
mVideoView.pause();
}
// super should be last in this method
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
if (mVideoUri != null) {
// for video, restores position it was playing
position = savedInstanceState.getInt("PositionVideo");
mVideoView.seekTo(position);
}
}
My complete class for reference, MakePhotoVideo.java:
package org.azurespot.makecute;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.azurespot.R;
import org.azurespot.cutecollection.CuteCollection;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MakePhotoVideo extends ActionBarActivity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final int ACTION_TAKE_VIDEO = 2;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private File fileVideo;
private String mCurrentPhotoPath;
String videoPath;
private int position = 0;
private RetainedVideoFragment videoFragmentData;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private PhotoStorageDirFactory mPhotoStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
mVideoView = (VideoView) findViewById(R.id.video_view);
mVideoView.setVisibility(View.INVISIBLE);
mImageBitmap = null;
mVideoUri = null;
mImageView.setSaveEnabled(true);
Button photoBtn = (Button) findViewById(R.id.click);
setBtnListenerOrDisable(
photoBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
Button videoBtn = (Button) findViewById(R.id.record_video);
setBtnListenerOrDisable(
videoBtn,
mTakeVidOnClickListener,
MediaStore.ACTION_VIDEO_CAPTURE
);
mPhotoStorageDirFactory = new BasePhotoDirFactory();
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void viewCollection(View v){
// finishes/restarts the activity so the unsaved video does not corrupt
Intent intent = getIntent();
finish();
startActivity(intent);
// goes to Cute Collection activity
Intent i = new Intent(this, CuteCollection.class);
startActivity(i);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mPhotoStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("Camera", "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;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
bitmap = rotateBitmap(bitmap, 90);
}
savePhoto(bitmap);
/* Associate the Bitmap to the ImageView, make sure the VideoView
* is cleared to replace with ImageView */
mImageView.setImageBitmap(bitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
// save your photo to SD card
private void savePhoto(final Bitmap bitmapPhoto){
// set OnClickListener to save the photo
mImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean success = false;
File photoDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + "/Cute Photos");
photoDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String photoName = "Photo"+ n +".jpg";
File filePhoto = new File (photoDir, photoName);
// if (filePhoto.exists ()) filePhoto.delete ();
try {
FileOutputStream out = new FileOutputStream(filePhoto);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute photo saved!",
Toast.LENGTH_LONG);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_SHORT).show();
}
}
});
}
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
boolean success = false;
if(event.getAction() == MotionEvent.ACTION_UP) {
try {
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Cute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video" + n + ".mp4";
fileVideo = new File(vidDir.getAbsolutePath(), videoName);
videoPath = fileVideo.getAbsolutePath();
Log.d("TAG", "Value of videoPath:" + videoPath);
fileVideo.setWritable(true, false);
OutputStream out = new FileOutputStream(fileVideo);
InputStream in = getContentResolver().openInputStream(uriVideo);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.close();
in.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast toast = Toast.makeText(getApplicationContext(), "Cute video saved!",
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
toastLayout.setBackgroundColor(getResources().getColor(R.color.toast_color));
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(30);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 80);
toast.show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_SHORT).show();
}
}
return true;
}
});
}
public Bitmap rotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.set(matrix);
matrix.setRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
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:
File f;
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);
}
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
private void handleCameraPhoto() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
// Post recorded video into VideoView
private Uri handleCameraVideo(Intent intent) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
mVideoView.start();
// saves video to file
saveVideo(mVideoUri);
return mVideoUri;
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
Button.OnClickListener mTakeVidOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakeVideoIntent();
// releases the orientation lock
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
};
// Intent data is how the photo and video transfer into their views
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO
case ACTION_TAKE_VIDEO: {
if (resultCode == RESULT_OK) {
handleCameraVideo(data);
}
break;
} // ACTION_TAKE_VIDEO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
if (mVideoUri != null) {
// use onSaveInstanceState in order to store the video or photo
outState.putInt("PositionVideo", mVideoView.getCurrentPosition());
// playback position for orientation change
mVideoView.pause();
}
// super should be last in this method
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
if (mVideoUri != null) {
// for video, restores position it was playing
position = savedInstanceState.getInt("PositionVideo");
mVideoView.seekTo(position);
}
}
/**
* 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);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Makes the UP caret go back to the previous fragment MakeCuteFragment
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Have you tried to save the bitmap into SD card directly?
Maybe you can use a flag, that indicates if the image is stored to load it when you return to your activity.
I think that onSaveInstanceState and onRestoreInstanceState is not thiked to save possible huge amount of date like bitmaps.
public static Bitmap readImage(Context context, String fileName){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getApplicationContext().getPackageName()
+ "/Photos");
String photoPath = mediaStorageDir.getPath() + File.separator + fileName;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
return bitmap;
}
public static String storeImage(Context context, Bitmap image, String birdName) {
String outputName = "";
File pictureFile = getOutputMediaFile(context, birdName);
if (pictureFile != null) {
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
outputName = pictureFile.getName();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return outputName;
}
private static File getOutputMediaFile(Context context, String birdName) {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getApplicationContext().getPackageName()
+ "/Photos");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
long timeStamp = System.currentTimeMillis();
File mediaFile;
String mImageName = birdName + "_" + timeStamp + ".png";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
Currently I am able to upload an existed image in the sdcard to my server. I'm a total newbie in Android programming world and I was wondering how do I dynamically grab the newly taken image and submit it to the server?
This is what I have so far for my onClick event
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
new Thread(new Runnable() {
public void run() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
//hard code
String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";
int response= uploadFile(path);
System.out.println("RES : " + response);
}
}).start();
}});
This is the codes for my camera functions
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
outStream.write(arg0);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
//VuzixCamera.super.onBackPressed();
}
camera.startPreview();
}};
Hope this answer will help you.
Take A new Picture Code:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class CameraUtil extends Activity {
private final static int REQUEST_TAKE_PHOTO=200;
private final String TAG = "Camera";
String mCurrentPhotoPath;
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(! isDeviceSupportCamera()){
Log.e(TAG,"Camera Not Supported");
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
}
else{
dispatchTakePictureIntent();
}
}
private void dispatchTakePictureIntent() {
Log.i(TAG,"Dispatch Take Picture Intent");
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
ex.printStackTrace();
Log.i(TAG,"Error occurred while creating the File");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
File file= new File(path);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && path!=null && file.length()>0) {
Intent returnFromCameraIntent = new Intent();
returnFromCameraIntent.putExtra("picturePath",path);
setResult(RESULT_OK,returnFromCameraIntent);
finish();
Log.i(TAG,"Camera Closed");
}else{
Log.i(TAG,"On Result CANCEL");
// cancelled Image capture
try{
/*delete Temperory created file*/
file.delete();
}catch(Exception e){
e.printStackTrace();
}
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
Log.i(TAG,"Image Capture Cancelled");
}
galleryAddPic();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
String imageFileName = "CAMERA_" + timeStamp + "_WA0001";
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyApp"+ File.separator);
if(!root.exists()){
root.mkdirs();
}
// File storageDir = Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
root /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
path=""+image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
}
Choose Existing Picture Code:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_LOAD_GALLERY=100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "Gallery_Image";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_GALLERY);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}else{
Log.i(TAG,"Image Capture Cancelled");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED,returnFromGalleryIntent);
finish();
}
}
}
Convert Image to Base64 String:
public class Base64Utils {
private static final String TAG = "Base64Utils";
private String picturePath;
private String base64;
public Base64Utils(String picturePath) {
this.picturePath = picturePath;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public String getBase64() {
FileInputStream fis11=null;
try {
fis11 = new FileInputStream(picturePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
byte[] buf = new byte[8096];
try {
for (int readNum; (readNum = fis11.read(buf)) != -1;) {
bos11.write(buf, 0, readNum);
}
} catch (IOException ex) {
ex.printStackTrace();
}
bytes = bos11.toByteArray();
base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
public void setBase64(String base64) {
this.base64 = base64;
}
}
Main Activity Code: Choose or Take Picture, convert it to base64 string and Send Base64 String to Server.
public class CapatureImage extends Activity implements View.OnClickListener {
private final String TAG = "CapatureImage";
String picturePath;
String base64 = null,
private ImageButton image;
// for popup
private PopupWindow pop;
private final int GALLERY_ACTIVITY_CODE = 200;
private final int CAMERA_ACTIVITY_CODE = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CapatureImage);
configureComponent();
}
private void configureComponent() {
image = (ImageButton) findViewById(R.id.image);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.image:
initiatePopupWindow();
break;
case R.id.button_camera_dialog:
Intent camera_Intent = new Intent(this.getApplicationContext(),
CameraUtil.class);
pop.dismiss();
this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
break;
case R.id.button_gallery_dialog:
Intent gallery_Intent = new Intent(this.getApplicationContext(),
GalleryUtil.class);
pop.dismiss();
this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
break;
case R.id.button_cancel_dialog:
pop.dismiss();
break;
case R.id.button_remove_dialog:
Log.i(TAG, "Remove Picture");
image.setImageResource(R.drawable.icon_781q);
picturePath=null;
pop.dismiss();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64();
//send this base64 string to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
if (requestCode == CAMERA_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
// Log.i("Camera_Activity", data.toString());
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}// onActivityResult
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialoge_choosephoto,
(ViewGroup) findViewById(R.id.photo_popup));
if (picturePath != null && !picturePath.isEmpty()) {
Log.i(TAG, "Image Exist..Add Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.VISIBLE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
} else {
Log.i(TAG, "No Image..remove Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.GONE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
}
// component for popup
gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
gallery.setOnClickListener(this);
camera = (Button) layout.findViewById(R.id.button_camera_dialog);
camera.setOnClickListener(this);
cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
cancel.setOnClickListener(this);
pop.showAtLocation(layout, Gravity.CENTER, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
void displayImage(String path) {
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
image.setScaleType(ScaleType.CENTER_CROP);
}
}
}
there is two classes upload and main_activity.And i here put it's xml file
public class MainActivity extends Activity {
final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final String TAG = "CaptureImage.java";
public static ImageView showImg = null;
static String uploadFilePath = " ";
static String Path;
static int delete_image_id = 0;
static TextView imageDetails = null;
// FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
static Cursor cursor = null;
public ProgressDialog dialog_upload = null;
public String s_name;
public String s_Adress;
int serverResponseCode = 0;
TextView shift_display;
Uri imageUri = null;
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("VALUES", "It is Working");
String fileName = "Camera_Example.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
};
MainActivity CameraActivity = null;
Upload upload;
Button outlet_names_show;
double latitude;
double longitude;
OnClickListener oclBtnOk3 = new OnClickListener() {
#Override
public void onClick(View v) {
if (showImg.getDrawable() == null) {
Toast.makeText(MainActivity.this, " Picture was not captured ",
Toast.LENGTH_SHORT).show();
} else {
upload_prescription();
// CallSummery.flag_bt_merchan=true;
}
}
};
private Button buttonback;
/**
* ********* Convert Image Uri path to physical path *************
*/
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String[] proj = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.getContentResolver().query(imageUri, proj, null,
null, null);
// Get Query Data
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int file_ColumnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// int orientation_ColumnIndex = cursor.
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
// imageDetails.setText("No Image");
} else {
if (cursor.moveToFirst()) {
imageID = cursor.getInt(columnIndex);
delete_image_id = imageID;
Path = cursor.getString(file_ColumnIndex);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Return Captured Image ImageID ( By this ImageID Image will load from
// sdcard )
return "" + imageID;
}
protected void onCreate(Bundle savedInstanceState) {
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraActivity = this;
showImg = (ImageView) findViewById(R.id.showImg);
upload = new Upload(MainActivity.this);
final Button photo = (Button) findViewById(R.id.photo);
final Button upload = (Button) findViewById(R.id.upload);
photo.setOnClickListener(oclBtnOk);
upload.setOnClickListener(oclBtnOk3);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageUri != null) {
outState.putString("cameraImageUri", imageUri.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
imageUri = Uri
.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void upload_prescription() {
dialog_upload = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
createDirectoryIfNeeded();
upload.uploadFile(uploadFilePath);
}
}).start();
}
private void createDirectoryIfNeeded() {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Capturetemp");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
}
public void copy(String lo, String lan) throws JSONException {
String sdCard = Environment.getExternalStorageDirectory().toString();
Random ran = new Random();
uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";
File sourceLocation = new File(Path);
File targetLocation = new File(uploadFilePath);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if (actionChoice == 1) {
if (sourceLocation.renameTo(targetLocation)) {
Log.v(TAG, "Move file successful.");
} else {
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else {
// make sure the target file exists
if (sourceLocation.exists()) {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
} else {
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ***************/
String imageId = convertImageUriToFile(imageUri, CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard(MainActivity.this).execute(""
+ imageId);
/*********** Load Captured Image And Data End ****************/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBackPressed() {
}
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
Context context;
Bitmap mBitmap;
private ProgressDialog loadingdailog;
public LoadImagesFromSDCard(MainActivity context) {
this.context = context;
}
#Override
protected void onPreExecute() {
loadingdailog = new ProgressDialog(context);
loadingdailog.setMessage("Loading Image.....");
loadingdailog.show();
}
// Call after onPreExecute method
#Override
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
uri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
+ urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
true);
// SaveIamge(newBitmap);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
// Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (loadingdailog.isShowing() && loadingdailog != null) {
loadingdailog.dismiss();
loadingdailog = null;
}
if (mBitmap != null) {
showImg.setImageBitmap(mBitmap);
}
}
}
}
upload class
public class Upload {
protected MainActivity context;
ProgressDialog dialog = null;
int serverResponseCode = 0;
String uploadFilePath = null;
String uploadFileName = null;
String msg = null;
String upLoadServerUri = "http://fileuploadpath";
public Upload(MainActivity context) {
this.context = context;
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("photo", fileName);
// conn.setRequestProperty("session_id","13");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
try {
readStream(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
context.runOnUiThread(new Runnable() {
public void run() {
context.dialog_upload.dismiss();
Toast.makeText(context, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
fileInputStream.close();
} catch (MalformedURLException ex) {
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// context.dialog.dismiss();
e.printStackTrace();
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
// context.dialog.dismiss();
return serverResponseCode;
}
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.e("tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/showImg"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="bla bla" />
<Button
android:id="#+id/photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Capture Image"
android:textSize="26sp" />
<Button
android:id="#+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Upload Photo"
android:textSize="26sp" />
</LinearLayout>
for image uri you should paste your file upload path
I use the below code to click photo in android phone but the captured image doesn't get saved in gallery. I'm new to android app development.Please verify this code and help me out.
package project.example.rivaa;
import java.io.File;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.VideoView;
public class PhotoIntentActivity extends Activity {
static String vid;
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 PNG_FILE_PREFIX = "IMG_";
private static final String PNG_FILE_SUFFIX = ".png";
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 imageFileName = PNG_FILE_PREFIX +vid+ "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, PNG_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;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
}
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() {
#Override
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.photointentactivity);
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();
Intent fd= new Intent("project.example.rivaa.OTP");
startActivity(fd);
}
break;
} // ACTION_TAKE_PHOTO_B
} // switch
}
// 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);
}
}
}
Your galleryAddPic() method doesn´t work? What if You try it like this:
String[] path = { mCurrentPhotoPath };
String[] type = {"image/jpeg"};
MediaScannerConnection.scanFile(this, path, type, null);
it is maybe not the solution, but to long for a comment..the type depends on what type You saved.
I´m using the google-android-example "Camera API".
Now I have put in a new Button called "btnGallery" to open the Gallery. If the User picks one Image, this Image should be displayed in main.xml -> imageView1 (also used for the preview of the camera-shot)
Is there any easy way to do this?
Thanks in advance!
package com.lo.android;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.database.Cursor;
public class PhotoIntentActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
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("lo", "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;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
}
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() {
#Override
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;
/// gallery picture path ///
Button picBtn = (Button) findViewById(R.id.btnShoot);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
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
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}// switch
// 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);
}
}
}
I found the sollution. Pls see it below btnGallery above in my code (edited). Thanks for all your help