Take Picture and Upload to Android Firebase Error [duplicate] - java

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.

Related

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[]

NullPointerException on intent when accessing Camera Android

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);
}
});
}
});
}
}

App crashing after taking picture and while delivering the result to onActivityResult

I am trying to take a picture by calling camera intent and show it in a image view. My code works on almost all devices except on some MI Devices with kitkat version. Here is my code
private void initializeCameraIntent() {
Permiso.getInstance().requestPermissions(new Permiso.IOnPermissionResult() {
/* if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED){*/
#Override
public void onPermissionResult(Permiso.ResultSet resultSet) {
if (resultSet.areAllPermissionsGranted()) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e(TAG, "onTileSelected: ", ex);
}
if (photoFile != null) {
Uri uri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
imageUri = uri.toString();
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} else {
Toast.makeText(MessagesFragment.this.getActivity(),
getString(R.string.msg_permission_required), Toast.LENGTH_LONG).show();
}
}
#Override
public void onRationaleRequested(Permiso.IOnRationaleProvided callback, String... permissions) {
Permiso.getInstance().showRationaleInDialog(null,
getString(R.string.msg_permission_required),
null, callback);
}
}, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
protected File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
if (!storageDir.exists()) {
if (!storageDir.mkdirs()) {
return null;
}
}
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
#Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
if (!imageUri.isEmpty()) {
showSendImageFragment(imageUri);
imageUri = "";
}
break;
}
And below is the exception thrown in some devices
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {com.xxx.xxx/com.xxx.xxx.view.activity.MainActivity}: java.lang.NullPointerException
Please Someone help me fixing this. It works on every Other device.
I think your imageUri is becoming null when your are calling startActivityForResult(intent) method you can replicate the issue on other devices by going to developer options enabling do not keep activities option to overcome this issue. Override onSaveInstanceState and onRestoreInstanceState methods in your activity
#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("imageUri"));
}
}
Its a MI devices Security issue.You wont be able to get the direct path of your selected file They will just provide only the content provider Url
I suggested you use this Coomar Picker Library.I also got stuck on the same issue for so many days.This is the only solution i have found it.This will save your time
And Here is the wiki for it WIKI

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)

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