NullPointerException on intent when accessing Camera Android - java

I am trying to call the Camera app twice as described here: https://developer.android.com/training/camera/photobasics
Now when I was using this without creating a temp file this worked and I was able to call the camera twice but after adding the temp file I am only able to take one file before crashing. it is very frustrating because I can see that it is returning a full size image before crashing.
I have tried doing a second .putExtras() before the get but that is not working. I have also tried assert not null, same results.
private void takePictureAndUpload() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.provider",
photoFile);
startActivityForResult(takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
, REQUEST_IMAGE_CAPTURE);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == REQUEST_IMAGE_CAPTURE) && (resultCode == Activity.RESULT_OK)){
count++;
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
assert imageBitmap != null;
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
final byte[] imageData = stream.toByteArray();
setuId(user);
final String path = "posts/" + UUID.randomUUID() + ".jpg";
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference imageRef = storageRef.child(path);
UploadTask uploadTask = imageRef.putBytes(imageData);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String ex = e.getLocalizedMessage();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
final String url = downloadUrl.toString();//do something with downloadurl
data.putExtra(MediaStore.EXTRA_OUTPUT, url);
addPhotoUrlToDatabase(post.getImageUrl_1(), post.getImageUrl_2(), path);
}
});
}
});
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
This should open the camera take a picture then after accepting the first picture it should reopen camera for a second picture. However so far all it does is open camera, take a picture then when I hit accept it crashes with a nullPointerException.
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android, PID: 21689
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.android/com.example.android.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4491)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4534)
at android.app.ActivityThread.-wrap20(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1752)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.android.MainActivity.onActivityResult(MainActivity.java:257)
at android.app.Activity.dispatchActivityResult(Activity.java:7547)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4487)
Edit
This is the guide that I am following:
https://developer.android.com/training/camera/photobasics.html#TaskPath

Make your activity result like this as using the same named parameters are confusing.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
}
Your Bundle seems like it's null.

Found an answer here:https://stackoverflow.com/a/37628687/10941659. It is not made clear on the android developer training site, but when you want to get a full size image you don't use the intent that you pass to onActivityResult. You need to use the path that you generate for your image, for example:
private void takePictureAndUpload() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == REQUEST_IMAGE_CAPTURE) && (resultCode == Activity.RESULT_OK)){
count++;
Bitmap imageBitmap = null;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),photoURI);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
final byte[] imageData = stream.toByteArray();
setuId(user);
final String path = "posts/" + UUID.randomUUID() + ".jpg";
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference imageRef = storageRef.child(path);
UploadTask uploadTask = imageRef.putBytes(imageData);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String ex = e.getLocalizedMessage();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
#Override
public void onSuccess(Uri downloadUrl)
{
final String url = downloadUrl.toString();//do something with downloadurl
addPhotoUrlToDatabase(post.getImageUrl_1(), post.getImageUrl_2(), path);
}
});
}
});
}
}

Related

I need a high quality image on my imageview, but I don't get any view in my imageview

This is my code for camera(i am using File Provider)
This is MainActivityMainActivity.java MainActivity.java
This is my display ActivityDisplayActivity.java
Plz help i tried so may codes and make projects again and again.
I am trying to get high quality image from the camera and display it on the imageview.
Here was an demo that can help with your project...
On Button Click...
//photoFile is global variable File photoFile = null;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 501);
}
} catch (Exception e) {
e.printStackTrace();
}
Put this method in your class
private File createImageFile() throws IOException {
long timeStamp = Calendar.getInstance().getTimeInMillis();
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
Get Result from camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 501:
if (photoFile != null) {
bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
if (bitmap != null) {
// you got bitmap here
}
}
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}

Android App crashes after capturing image using camera intent

The application attempts to capture an image using the device's camera and upload it to FireBase. However, after an image is captured, the app crashes.
It shows the error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
Functions in MainActivity:
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e("MainActivity", "Error creating file", e);
}
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance().getReference();
take_pic = (Button) findViewById(R.id.take_pic);
imageView = (ImageView) findViewById(R.id.pic_view);
progressDialog = new ProgressDialog(this);
take_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
progressDialog.setMessage("Uploading...");
progressDialog.show();
StorageReference filepath;
Uri uri = data.getData();
filepath = storage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(photoURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
You are getting that errror because your intent.getData is null. It happened to me too, your onActivityResult when using the take picture intent always brings the data as null. As a workaround I made the photoURI a global variable in the activity and onActivityResult called it again. It would be something like this:
First you declare the variable
Uri myPhotoUri = null;
Then, you initiate it in your dispatchTakePictureIntent function:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e("MainActivity", "Error creating file", e);
}
if (photoFile != null) {
//you are adding initializing the uri
myPhotoUri = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
And on your onActivityResult, you use that uri to call to your firebase function. It will now have the information necessary to upload it:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
progressDialog.setMessage("Uploading...");
progressDialog.show();
StorageReference filepath;
//you delete the Uri uri = data.getData();
filepath = storage.child("Photos").child(uri.getLastPathSegment());
//here you call it
filepath.putFile(myPhotoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
First check that you have permission for using the camera, then
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
Then onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQ && resultCode == Activity.RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
Bitmap.createScaledBitmap(bitmap, 150, 150, true);
}
}
then from bitmap to byte[]
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if(bitmap == null) return null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
You can now do whatever you want with the bitmap or byte[]

Image rotates after bitmap.compress

So i'm trying to get the user to pick an image from their photo gallery then upload it to Firebase Storage...so far my code looks as follows:
#Override
protected void onActivityResult(int requestCode,int resultcode, Intent data){
super.onActivityResult(requestCode,resultcode,data);
if(requestCode == REQUEST_IMAGE_CAPTURE && resultcode == RESULT_OK) {
final Uri uri = data.getData();
if (uri != null){
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e){
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 25, baos);
byte[] fileInBytes = baos.toByteArray();
bmp.recycle();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
String imageString = "";
if(clickPhoto ==1){imageString = "Image 1"; }
else if(clickPhoto ==2){imageString = "Image 2"; }
else if (clickPhoto ==3){imageString = "Image 3"; }
else if (clickPhoto ==4){imageString = "Image 4"; }
final StorageReference storageReference = storage.getReference().child("Images").child("users").child(auth.getCurrentUser().getUid()).child(imageString);
storageReference.putBytes(fileInBytes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
String urlString ="";
if(clickPhoto ==1){ urlString = "photo1URI";}
if(clickPhoto ==2){ urlString = "photo2URI";}
else if (clickPhoto ==3){ urlString = "photo3URI";}
else if (clickPhoto ==4){urlString = "photo4URI";}
toMap.put(urlString, downloadUrl);
updatedb();
toMap.clear();
Log.d("uriii",downloadUrl);}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("UploadFailure",e.getMessage());
}
});
}
else {
Toast.makeText(this,"Didn't work",Toast.LENGTH_LONG).show();
}
}
}
My problem is that the image that is uploaded changes orientation...seeminly at random....how do i maintain orientation? I've looked at Exif interface but can't see an answer for uploading it as a ByteArrayOutputStream?
Any help would be appreciated.
Issue is that EXIF information from image (including orientation) is removed after compressing. You need to copy EXIF info from original image to compressed one. Solution explained here.

Take Picture and Upload to Android Firebase Error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm write a simple code to instant camera image capture and upload it to android firebase.
From Referance Here
Try to write full code as android studio documentation.
But in logcat we can show this code occur an error uri.getLastPathSegment().
How can solve this error?
Error Logcat:
--------- beginning of crash
05-23 14:52:06.627 12364-12364/com.example.hasib_pc.firebasetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hasib_pc.firebasetest, PID: 12364
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { }} to activity {com.example.hasib_pc.firebasetest/com.example.hasib_pc.firebasetest.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:4268)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
MainActivity Full code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final int IMAGE_CAPTURE_CODE = 3;
private Button uploadBtn;
private ImageView showImage;
private StorageReference mStorage;
private ProgressDialog progressDialog;
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
Log.d(TAG, "createImageFile: start.");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.d(TAG, "createImageFile: End.");
return image;
}
private void takePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e(TAG, "takePictureIntent: IOException: "+ex.getMessage(),ex);
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, IMAGE_CAPTURE_CODE);
Log.d(TAG, "takePictureIntent: End.");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
uploadBtn = findViewById(R.id.uploadBtnId);
showImage = findViewById(R.id.imageShowId);
progressDialog = new ProgressDialog(this);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
takePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: Started.");
if(requestCode == IMAGE_CAPTURE_CODE && resultCode == RESULT_OK){
Log.d(TAG, "onActivityResult: start uploading");
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
Log.d(TAG, "onActivityResult: set filepath");
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
Log.d(TAG, "onActivityResult: try to putFile");
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onSuccess: started.");
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
It was my mistake. I found the solution.
Create a Uri instantce veriable. private Uri photoURI;
Then send this Uri with Intent putExtra method.
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
and pass the uri object via StorageReference putFile method
filepath.putFile(photoURI)
I called Uri photoURI in onCreate method insted of Class instance veriable that's why got NullPointerException.

Nothing happens when I press the button to accept a picture

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)

Categories

Resources