How do I set the Camera Intent as the Main Activity - java

I want to launch the camera once a user opens up my application.
Right now I have this, and it works fine. When the user launches my application, it automatically opens up the camera. However, then the user hits the "back" button after taking an image, it opens up a blank activity.
How do I get it to go back to the camera?
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 0;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
takePhoto();
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent(MainActivity.this, Result.class);
intent.setData(imageUri);
startActivity(intent);
}
}
// Launch the camera to allow the user to take a photo
public void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
}
}
}
}

Try to call takePhoto() method in the onStart() instead of onCreate() and then call the finish() method into the onStop().

Try it.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ActivityYouWantToOpen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}

Related

How to launch activity from non-activity class and receive the onActivityResult() on the activity class

I have one class that extends from fragment, and another class, which is a non-activity class that starts some intents (camera related stuff).
I pass the first one to the constructor on the second one so the second one can perform the creation of intents and start them. But I expect that the onActivityResult gets called on the activity side, the Fragment, but it never gets called. What I'm doing wrong?
Fragment class:
public class MyFragment extends Fragment
{
private static final String TAG = "Example";
private NonActivityClass nonActivityClass = null;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
nonActivityClass = new NonActivityClass(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(TAG, "ON RESULT");
if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK)
{
Log.d(TAG, "ON RESULT!");
}
}
}
Non-activity class:
public class NonActivityClass
{
private Activity activity;
static final int REQUEST = 1;
public NonActivityClass(Activity activity)
{
this.activity = activity;
}
private Activity getActivity()
{
return this.activity;
}
public void DispatchTakePictureIntent()
{
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = CreateImageFile(); //this method creates the temporary file, shouldn't be relevant
}
catch (IOException ex)
{
Log.d(TAG, "Error occurred while creating the File:" + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//THIS
getActivity().startActivityForResult(takePictureIntent, REQUEST);
//
}
}
}
}
}
EDIT:
Even following this answer: call to startActivityForResult() from non activity class and getting result in existing activity or fragment
and instead of pasing the activity passing the fragment, it doesn't call onResult.
Looking close to the answer that I post on my question: call to startActivityForResult() from non activity class and getting result in existing activity or fragment
I've noticed that the problem is that I was calling startActivityForResult() from Activity, and should be called from the fragment. So instead passing Activity to my class, I refractored like the answer to use Fragment.
So fragment code will look like:
public class MyFragment extends Fragment
{
private static final String TAG = "Example";
private NonActivityClass nonActivityClass = null;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
RequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
nonActivityClass = new NonActivityClass(this); //this, instead of getActivity()
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(TAG, "ON RESULT");
if (requestCode == NonActivityClass.REQUEST && resultCode == RESULT_OK)
{
Log.d(TAG, "ON RESULT!");
}
}
}
And non-activity class like:
public class NonActivityClass
{
private Fragment fragment;
static final int REQUEST = 1;
public NonActivityClass(Fragment fragment)
{
this.fragment = fragment;
}
private Activity getActivity()
{
return this.fragment.activity;
}
public void DispatchTakePictureIntent()
{
Log.d(TAG, "DISPATCH");
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = CreateImageFile(); //this method creates the temporary file, shouldn't be relevant
}
catch (IOException ex)
{
Log.d(TAG, "Error occurred while creating the File:" + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//THIS
fragment.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//
}
}
}
}
}

Trying to display image taken from camera intent

I'm Currently trying to take a photo from the default camera intent from the MainActivity and then put that image in an ImageView in the same activity.
I'm saving the images such that the image taken overwrites the previously taken image (In this case, I call the image test.jpg and I store it in sdcard)
The problem I have with my code right now is the ImageView displays the photo taken the previous time the application ran.
Here is my code.
public class MainActivity extends Activity
{
ImageView imv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imv = (ImageView)findViewById(R.id.imv);
Uri uri = null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.jpg";
try
{
uri = takePhoto(path);
}
catch(Exception e)
{
e.printStackTrace();
}
imv.setImageURI(uri);
}
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}
}
Try to set image in onActivityResult as below:
protected void onActivityResult(int requestCode, int resultCode, Intent ata)
{
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
imv = (ImageView)findViewById(R.id.imv);
Bitmap photo = (Bitmap) data.getExtras().get("data");
imv.setImageBitmap(photo);
}}}
private static final int PICK_CONTACT_REQUEST = 0 ;
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
imv.setImageURI(uri);
}
}
}
Set the image in onactivity result it will show new Image taken from the camera .
Try this,
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
if(photo.exists())
photo.delete();
photo = new File(path);
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}

MediaStore.EXTRA_OUTPUT renders data null, other way to save photos?

Google offers this versatile code for taking photos via an intent:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
The problem is that if you're like me and you want to pass the photos as extras, using EXTRA_OUTPUT seemingly runs off with the photo data and makes subsequent actions think the intent data is null.
It appears this is a big bug with Android.
I'm trying to take a photo then display it as a thumbnail in a new view. I'd like to have it saved as a full sized image in the user's gallery. Does anyone know a way to specify the image location without using EXTRA_OUTPUT?
Here's what I have currently:
public void takePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "JoshuaTree");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("JoshuaTree", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
handleSmallCameraPhoto(data);
}
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", mImageBitmap);
startActivity(displayIntent);
}
}
If you specified MediaStore.EXTRA_OUTPUT, the image taken will be written to that path, and no data will given to onActivityResult. You can read the image from what you specified.
See another solved same question here: Android Camera : data intent returns null
Basically, there are two ways to retrieve the image from Camera, if you use to send a captured image through intent extras you cannot retrieve it on ActivityResult on intent.getData() ' because it saves the image data through extras.
So the idea is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
And retrieving it on ActivityResults checking the retrieved intent:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (intent.getData() != null) {
ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(intent.getData(), "r"); 
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} else {
Bitmap imageRetrieved = (Bitmap) intent.getExtras().get("data");
}
}
}
}
Here is how you can achieve what you want:
public void onClick(View v)
{
switch(v.getId())
{
case R.id.iBCamera:
File image = new File(appFolderCheckandCreate(), "img" + getTimeStamp() + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_RESULT);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RESULT:
if(resultCode==RESULT_OK)
{
handleSmallCameraPhoto(uriSavedImage);
}
break;
}
}
private void handleSmallCameraPhoto(Uri uri)
{
Bitmap bmp=null;
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", bmp);
startActivity(displayIntent);
}
private String appFolderCheckandCreate(){
String appFolderPath="";
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage.canWrite())
{
appFolderPath = externalStorage.getAbsolutePath() + "/MyApp";
File dir = new File(appFolderPath);
if (!dir.exists())
{
dir.mkdirs();
}
}
else
{
showToast(" Storage media not found or is full ! ");
}
return appFolderPath;
}
private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS").format(cal.getTime());
return timeString;
}
Edit:
Add these to Manifest:
Starting Api 19 and above READ_EXTERNAL_STORAGE should be declared explicitly
*<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to you manifest.
Try this one android.provider.MediaStore.EXTRA_OUTPUT hope will solve your bug. The following code works for me:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
I was facing same problem, every time getting null while retrieving data on other activity with getIntent().getData() then solved by writting complete android.provider.MediaStore.EXTRA_OUTPUT this solved my bug.

capturing image using camera in Android

Hi stackoverflow friends,
I need to take a picture using camera and after takin the picture go to next activity without showing the first activity. And display it in an imageview.
Below is the flow of my application
first activity-> there is button for camera intent->go to the next activity(without showing the fist activity) second activity->there i need to show the image in imageview.
I saw a lot of examples of camera intent nobody explains how to go to the next activity without showing the first and display it in imageview of second.
Any outofmemeory problem occurs while displaying images in imageview repeatedly?
Thanks in advance
In First activity :
Button b=(Button)findViewByid(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == CAMERA_RESULT) {
Intent intent = new Intent(this, nextimage.class);
// here you have to pass absolute path to your file
intent.putExtra("image-path", mUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
finish();
}
}
In nextimage.class you can set one image view and get the imagepath from putExtra and place it in imageview.
String mImagePath = extras.getString("image-path");
Bitmap mBitmap = getBitmap(mImagePath);
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in);
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
place the bitmap in the imageview.you have to create imageview in secondActivity.
use a camera intent....here's a simple code
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraIntent extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
Get Bundle extras = intent.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
imv = (ImageView) findViewById(R.id.ReturnedImageView);
imv.setImageBitmap(bmp);
}
}
}
Use Following Code for that, it will solve your problem.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult() Method:-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
bmpImage = (Bitmap) data.getExtras().get("data");
drawable = new BitmapDrawable(bmpImage);
mImageview.setImageDrawable(drawable);
}
}
}

OnClickListener class does not open camera

I currently have a MainActitivty.java and want to make a PhotoActitivty.java to clean it up and allow for every button or action to have its own class. For some reason my new PhotoActivity class won't open up the camera intent.
I have something like this:
public class MainActivity extends AppCompatActivity {
private Button firstPictureButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
firstPictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), PhotoActivity.class));
}
});
}
}
I started a new class and called it PhotoActivity.java to call this class every time a button for camera intent had been clicked.
What I currently have is:
public class PhotoActivity extends AppCompatActivity implements View.OnClickListener {
private final int REQUEST = 1;
private File image;
private String pathToFile;
private ImageView imageView;
#Override
public void onClick(View view) {
imageView = findViewById(R.id.imageView);
dispatchTakePictureIntent();
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Make sure there's camera activity to handle the camera intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create an empty File for the soon created File
File photoFile = null;
try {
photoFile = createImageFile();
} catch (Exception e) {
// Error when creating the File
e.printStackTrace();
}
// If File created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.inventorymanager.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST);
}
}
}
public File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save the file's path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
The problem with this is that whenever it opens, onClickListener, the camera doesn't open even though my dispatchTakePictureIntent() method is there.

Categories

Resources