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.
Related
im trying to have my apps submit button not clickable until the user takes a picture. so initially the button will be not clickable and then when the person takes a picture the submit button becomes clickable so they can move on. problem is i cant get it to work properly. as of right now the submit button is not clickable (which is what i want) when it first loads. but if i hit the camera button then press the back button the submit button becomes visible(i want it to be unclickable). how can i correct this so that it doesnt show the submit button during this situation? o far i have tried to set not clickable in the oncreate method , and i set to clickable when the image file is made in the photobutton. which didnt work.
public class TreeQuestionsActivity extends AppCompatActivity {
Button btnSubmit;
Button btnPhoto;
ProgressBar progress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tree_questions_list);
btnSubmit = (Button) findViewById(R.id.enter_button);
btnPhoto = (Button) findViewById(R.id.photo_button);
btnSubmit.setEnabled(false);
}
private void setupButton() {
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selection();
if (mCurrentPhotoPath == null) {
Toast.makeText(getApplicationContext(), "Please submit a picture of the tree before you move on",
Toast.LENGTH_LONG).show();
} else if (f == false) {
showProgress(true);
new UploadTreeTask().execute(); //adds tree and then adds the dailyUpdate -> Goes to bird list activity
//new DbInsertTask().execute();
} else {
showProgress(true);
treeID = tree.getId();
new UploadDailyTask().execute();
}
}
});
btnPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, ACTIVITY_START_CAMERA);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
// Error occurred while creating the File
Log.i(Constants.TAG, "IO Exception");
e.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
btnSubmit.setEnabled(true);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "TREE_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.d(Constants.TAG, mCurrentPhotoPath);
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ACTIVITY_START_CAMERA:
if (requestCode == ACTIVITY_START_CAMERA && resultCode == RESULT_OK & null != data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//to generate random file name
String fileName = "tempimg.jpg";
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//captured image set in imageview
imageView.setImageBitmap(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
move this line
btnSubmit.setEnabled(true);
to onActivityResult() method after this line
imageView.setImageBitmap(photo);
your code looks fine but i think it would look better if you just played with the visibility of the button:
btnSubmit.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
and you have to to add :
btnSubmit.setEnabled(true);
into your onActivityResult() method
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();
}
I made a class(ShowPhoto.java) which can make and save a photo. But nothing is happening when I click the "V" in my photo maker. So it makes the photo, but when you verify the photo, the app gives an error. When I press this button, the app should save the photo. Any idea what I forgot to add in my code?
package com.example.photoviewer;
//imports here
public class FotoMaker extends Activity
{
private static final String LOG_TAG = "debugger";
ImageView iv;
// Uri uriOfPicture;
static final int REQUEST_TAKE_PHOTO = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_pic);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
dispatchTakePictureIntent();
Log.i(LOG_TAG, "test5");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
Log.i(LOG_TAG, "test3");
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
Log.i(LOG_TAG, "test");
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(LOG_TAG, "test1");
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
Log.i(LOG_TAG, "test2");
}
}Log.i(LOG_TAG, "test4");
}
}
LogCat:
11-17 21:12:39.960: E/AndroidRuntime(15260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.keyfinder/com.example.photoviewer.FotoMaker}: java.lang.NullPointerException
11-17 21:12:39.960: E/AndroidRuntime(15260): at com.example.photoviewer.FotoMaker.onActivityResult(FotoMaker.java:61)
I cannot figure out why this is occurring. It is probably a silly mistake that I cannot identify. Again the error is:
getOutputMediaFile(int) is undefined for the type new Camera.PictureCallback(){}
my code:
public static final int MEDIA_TYPE_IMAGE = 1;
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
//Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
// Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
If you arrived here because of the camera example scroll down further into the documentation the method is written at the last as it's common to both video and the image capture
http://developer.android.com/guide/topics/media/camera.html#saving-media
See Camera Android Code
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
Uri fileUri ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri= getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").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 == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
TextView tv=(TextView)findViewById(R.id.textView2);
if (resultCode == RESULT_OK) {
tv.setText("Image saved to:\n"+data.getData());
ImageView img=(ImageView)findViewById(R.id.imageView1);
img.setImageURI(fileUri);
//tv.setText(fileUri.toString());
} else if (resultCode == RESULT_CANCELED) {
tv.setText("Cancelled");
} else {
// Image capture failed, advise user
tv.setText("Can con be captured");
}
}
}
}
Edit
Try importing android.provider.MediaStore.Files.FileColumns and change MEDIA_TYPE_IMAGE to FileColumns.MEDIA_TYPE_IMAGE.
if you are calling Camera like
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);
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;
}