I am absolutely new to Android as well as Java (only some basic knowledge). I am trying to develop a simple app as per a youtube video. In this app, I have a button which is clickable and call the method launchCamera(). The image captured by the camera has to be displayed in the ImageView.
PROBLEM: I installed the .apk file in my mobile. When I click the "Take Photo" button, my camera starts. When I capture a image from my camera and save it, that image gets displayed in the ImageView only for a second (even less then a second). How can I keep that photo in the ImageView till the user does not press the "Take Photo" button again?
UPDATE: With the same code, I just noticed something strange. Mostly the image captured while holding the phone vertically rotates itself inside the ImageView and disappears. But sometimes it stays in the ImageView vertically and doesn't get disappeared till the "Take Photo" button is pressed again (Desired case).
My Code:
package com.siddexample.buttonimage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ButtonImageMainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView siddImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_image_main);
Button siddButton = (Button) findViewById(R.id.siddButton);
siddImageView = (ImageView) findViewById(R.id.siddImageView);
}//////-------------///////////////
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture by your intent
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
siddImageView.setImageBitmap(photo);
}
}
}
Try using this tutorial here , as follows:
Taking a picture:
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
Receiving the picture:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
and displaying the picture:
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
As #stkent said, maybe the onActivityResult is called twice.
Related
I have some troubles to display images in OpenGL.
Actually I'm able to display images from gallery in opengl. The problem occurs when I try to show one from the camera.
For me, OpenGL have to display the image from the camera as it does with the gallery ones. Obviously I'm making something wrong.
Any help will be appreciated.
Intent from gallery:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult(intent, 2);
Intent from camera:
Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File imagen = controler.createPhotoFile(getExternalFilesDir(Environment.DIRECTORY_PICTURES));
if (imagen != null) {
photoUri = FileProvider.getUriForFile(this, "my.fileprovider", imagen);
takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePic, 1);
}
}
This is my onActivityResult where I send the URI to a method which convert it to a bitmap and send it.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1:
sendImagenPanel(photoUri);
break;
case 2:
sendImagenPanel(data.getData());
break;
}
}
}
private void sendImagenPanel(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
final Bitmap imagen = controler.getCroppedBitmap(controler.scaledBitmap(bitmap, 256));
final CasillaOG casilla = ((GLSurfacePanel) gLViewPanel).getRendererPanel().getCuboSelected();
gLViewPanel.queueEvent(new Runnable() {
#Override
public void run() {
casilla.loadNewTexture(imagen);
casilla.setImagen(imagen);
}
});
gLViewPanel.requestRender();
}
In case someone is interested. I realize that the problem is not on the method that calls OpenGL. If I run the same code on the onActivityResult works from the gallery requestCode but not on the camera one, in my Samsung Galaxy Tab A. Why I mention my device? because if I run the app on a Huawei P9 lite, the gallery images are not display either. In both cases appears the next problem on the console:
call to opengl es api with no current context (logged once per thread)
After search that problem, I suppose that the intents of the camera and gallery use OpenGL and its originate a conflict with my own OpenGL environment.
Finally, I opted to set a bitmap field and add the texture in on the onDrawFrame. Obviously, with a boolean to make it one time.
Currently running fragment closes and gets back into previous activity when trying to import photo from gallery and set it to ImageView.
I want to set the imported image to an ImageView which is in the fragment. But when I select the image it closes the current fragment and goes back to the previous activity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == 1000){
try {
Uri returnUri = data.getData();
Bitmap bitmapImage = null;
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
ImageView iv = getView().findViewById(R.id.profile_image);
iv.setImageBitmap(bitmapImage);
getFragmentManager().popBackStackImmediate();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want choose an image from the gallery and set it to an ImageView which is in the currently running fragment without getting closing it.
I tried putting getFragmentManager().popBackStackImmediate(); in OnActivityResult() in my fragment. But it doesn't work.
I'm trying to upload an image taken by the camera in an android application to Firebase storage. The problem is that after I take the picture, in the confirmation activity, I pressed the confirm button and it says that "Unfortunately the application stopped".
This is the image when I press the check button, and the app crashes...
This is my code, the application has the option to upload pictures using the gallery and the camera.
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private Button selectImage;
private Button selectImageByCamera;
private ImageView imageView;
private StorageReference storageReference;
private ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int GALLERY_INTENT= 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
storageReference=FirebaseStorage.getInstance().getReference();
/*
* Code section to upload an image using the Gallery.
*/
selectImage=(Button)findViewById(R.id.btn_uploadImg);
progressDialog = new ProgressDialog(this);
selectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
/*
* Code section to upload an image using the Camera.
*/
selectImageByCamera=(Button)findViewById(R.id.btn_uploadImgCamera);
imageView=(ImageView)findViewById(R.id.imageView);
selectImageByCamera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//Upload the image to Firebase Update
if(requestCode==GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
//Code to upload image taken by the camera to firebase storage
if(requestCode==CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri2 = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri2.getLastPathSegment());
filepath.putFile(uri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
{
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have this USER PERMISSIONS in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
I have this Firebase dependencies in app/build.gradle
compile 'com.google.firebase:firebase-core:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'
compile 'com.google.firebase:firebase-auth:9.8.0'
And finally this is the exception thrown when I run the app in my Moto G4 6.0.1 (The app has permissions to use Camera and Gallery)
FATAL EXCEPTION: main
Process: mx.com.jamba.jamba, PID: 16543
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {mx.com.jamba.jamba/mx.com.jamba.jamba.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at mx.com.jamba.jamba.MainActivity.onActivityResult(MainActivity.java:186)
at android.app.Activity.dispatchActivityResult(Activity.java:6470)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
I don't know what to do, it would be great if you guys to help me :)
Thank you!
The exception occurs because the Uri in onActivityResult() is null:
Uri uri = data.getData();
The documentation for capturing a camera image explains:
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Follow the example in the documentation to create a file Uri and add it to the intent for the camera app.
Please try this
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
select.setImageBitmap(mImageUri);
}
then start posting
i have create an android application that will capture picture and save in sdcard folder,now i want to save the image with a custom name.
import java.io.ByteArrayOutputStream;
import android.view.Menu;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "new-photo-name.jpg");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
MediaStore.Images.Media.insertImage(getContentResolver(), photo,
null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
}
}
here is the code which i have used for capturing the image and save them in the sd card folder,please help me to save the image with a specific name for eg:android.jpeg
File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg");
FileOutputStream fos = new FileOutputStream(outFile);
photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
you would also need to add Permission in Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
the snippet will save the content of photo inside /sdcard with the name "myname.jpeg"
You need to put fileName as Intent Extras -
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "android.jpg");
this article maybe useful, try it.
& this as well, the only different that he used the date as a default name.
change it.
It usually works :)
I'm following this tutorial: http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/
I am trying to create a simple activity that has a "take picture" Button, and an ImageView, and simply take a picture, then open the cropping activity built into Android. I can open the camera without incident, however, upon taking the photo, the code doesn't send the photo to the cropping activity.
It seems to crash when the cropping activity is called. I'm not sure why this is occurring; I followed the example exactly (except for the beginning XML stuff which I didn't need), and I looked over the code and everything seems to make sense. I'm sure it's a minor error somewhere that is causing this. Here is my code for the activity:
package com.example.project;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageChoose extends Activity implements OnClickListener {
//keep track of camera capture intent
final int CAMERA_CAPTURE = 1;
//captured picture uri
private Uri picUri;
final int PIC_CROP = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_choose);
Button takePicture = (Button)findViewById(R.id.takePicture);
takePicture.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.takePicture){
try{
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
}catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Your device doesn't support photos!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
if (requestCode == CAMERA_CAPTURE){
picUri = data.getData();
performCrop();
}else if(requestCode == PIC_CROP){
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView picView = (ImageView)findViewById(R.id.picture);
//display the returned cropped image
picView.setImageBitmap(thePic);
}
}
}
private void performCrop(){
try{
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}catch(ActivityNotFoundException anfe){
String errorMessage = "Your device doesn't support photo cropping!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
I have used this type of action.Here is my code with the following link:-Detail Description
I hope this will help you.I suggest you the following Lines where you should have your focus:-
Intent camera=new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
The cropping activity is part of the stock Android camera app. It may or may not be available on your device, especially if you are using a custom/vendor camera app. If you want this to work reliably, you have to take the code for the cropper and incorporate it into your own app.
private void performCrop(){
}
Inside this method we are going to call an Intent to perform the crop, so let’s add “try” and “catch” blocks in case the user device does not support the crop operation:
try {
}
catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
//keep track of cropping intent
final int PIC_CROP = 2;