I am selecting a image from gallery and trying to covert it into pdf using itext , but when i selecting the image its app crashes with null pointer excetion
when i logged the picture path getting null( String picturePath = cursor.getString(columnIndex);)
code for the same
final private int SELECT_PICTURE = 201;
select_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch(requestCode){
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmp = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=201, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:87703 flg=0x1 }} to activity {com.example.pdfcreator/com.example.pdfcreator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4423)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4465)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.example.pdfcreator.MainActivity.onActivityResult(MainActivity.java:159)
at android.app.Activity.dispatchActivityResult(Activity.java:7590)
at android.app.ActivityThread.deliverResults(ActivityThread.java:441
solved Intent.ACTION_PICK solved my issue.
i was using this answer How to convert images to pdf using iText , as he used action ACTION_GET_CONTENT
can any one tell me why ACTION_GET_CONTENT not working here?
Related
I am developing an application for Android which is supposed to take pictures from camera and upload those images to database. However, the app runs fine for first 8-10 pictures, but when I attempt to take more pictures the app gets crashed.
The error from log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.salesservice, PID: 18379
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.project.salesservice/com.project.salesservice.user.UserVisitDetailActivity}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:5195)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5236)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2187)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8057)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:496)
at android.net.Uri$StringUri.<init>(Uri.java:486)
at android.net.Uri.parse(Uri.java:458)
at com.project.salesservice.user.UserVisitDetailActivity.getImageUri(UserVisitDetailActivity.java:582)
at com.project.salesservice.user.UserVisitDetailActivity.onActivityResult(UserVisitDetailActivity.java:558)
at android.app.Activity.dispatchActivityResult(Activity.java:8516)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5188)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5236)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2187)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8057)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
Code for starting intent
imageUri = null;
Intent takePictureIntent = new Intent();
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
takePictureIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
On Activity Result Code
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == UserVisitDetailActivity.RESULT_OK && data != null){
System.out.println("Masuk Camera");
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageUri = getImageUri(getApplicationContext(), photo);
if(checkInOut.getText().equals("Check In")) {
System.out.println(imageUri);
checkInHolder.setVisibility(View.VISIBLE);
checkInHolder.setImageURI(imageUri);
} else if(checkInHolder.getVisibility() == View.VISIBLE && checkInOut.getText().equals("Check Out")) {
System.out.println(imageUri);
checkOutHolder.setVisibility(View.VISIBLE);
checkOutHolder.setImageURI(imageUri);
}
}
}
Get Image URI Code
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
The problem is solved when the photos stored in the gallery are deleted. And the app will start to crash again if the photos reach 10 in gallery. Sorry if my grammar is not correct.
Really appreciate for your help. Thank you
Maybe you can optimize your image taking. The lack of memory on the device may be one of the cause of this problem. If there is not enough memory, the program may crash since taking pictures uses up memory. You might think about compressing the pictures before submitting them to the database or putting in place a system that releases memory after each picture is taken to solve this problem.
You could also check if the call to the MediaStore.Images.Media.insertImage method returns an empty string which is then passed to the Uri.parse method causing a NullPointerException. You should check if the MediaStore.Images.Media.insertImage method actually returns a valid value. If it does not, you should consider using another method to insert the image into the internal storage.
My Android app wants to create a folder in Google Drive and get the uri from the Drive app on the device.
It sends an intent, you can see the code below:
private void createFolder(String folderName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested MIME type.
intent.setType("vnd.android.document/directory");
intent.putExtra(Intent.EXTRA_TITLE, folderName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
then it gets the returned data, you can see the code below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData)
{
if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("result", "Uri: " + uri.toString());
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri); //this line gives the error
}
}
}
I used a mimetype found on the internet that seems to be a standard type. The same error is issued when using "application/vnd.google-apps.folder".
The goal is to have a document tree but in logcat I get the following error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=43, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=encoded=LongStringWithRandomCharactersHere/j flg=0x43 }} to activity {com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3DSameLongStringWithRandomCharactersHere%2Fj
and below
Caused by: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3DAnotherLongStringWithDifferentRandomDataHere
Here's the complete stack trace:
2019-05-31 15:06:50.167 31184-31184/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 31184
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=43, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=encoded=randomcharacters flg=0x43 }} to activity {com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3Drandomcharacters
at android.app.ActivityThread.deliverResults(ActivityThread.java:4365)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4409)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
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:810)
Caused by: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3Drandomcharacters
at android.provider.DocumentsContract.getTreeDocumentId(DocumentsContract.java:1023)
at android.support.v4.provider.DocumentFile.fromTreeUri(DocumentFile.java:138)
at com.example.myapplication.MainActivity.onActivityResult(MainActivity.java:254)
at android.app.Activity.dispatchActivityResult(Activity.java:7295)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4361)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4409)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
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:810)
The uri is not wrong because I can further extract the name of the folder (and the size=0), that is successfully created on the Drive cloud.
What's wrong instead? It seems that my app cannot handle it as a document tree.
This is working with Google Drive cloud space but maybe it's a hack. It is not guaranteed to always work.
This example creates a cloud file in a cloud folder that was created by the user (the SAF picker is opened by the app).
Creating the cloud folder (the user has to select the cloud root first from the picker UI)
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType("vnd.android.document/directory");
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CREATE_DIRECTORY_REQUEST_CODE);
onActivityResult
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CREATE_DIRECTORY_REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK) {
int takeFlags = data.getFlags()
&
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
ContentResolver resolver = this.getContentResolver();
resolver.takePersistableUriPermission(data.getData(),takeFlags);
archiveUri(data.getData().toString()); //important to save the toString() result, not getPath()
archiveAuthority(data.getData().getAuthority());
}
else
{
// The user cancelled the request.
}
}
}
using the Uri next time
ContentResolver contentResolver;
contentResolver = this.getContentResolver();
uriPath=retrieveArchivedUri();
Uri tempUri;
Uri uri;
String authority;
tempUri=Uri.parse(uriPath);
authority=retrieveArchivedAuthority();
uri= DocumentsContract.buildDocumentUri(authority,
DocumentsContract.getDocumentId(tempUri)); //folder Uri
try
{
DocumentsContract.createDocument(contentResolver,uri,"plain/text","fileName");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Activity results is NullPointerException, What I have done wrong or missed?
Photo gallery application(Eventually), followed the instructions on the android developer site about taking photos with inbuilt camera. onActivityResult giving null pointer. I am new to android so can't figure it out.
Because of this it crashes, i expect it to show a bitmap in the activity.
public class aCamera extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
ImageView imageView;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_camera);
dispatchTakePictureIntent();
}
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) {
File photoFile = null;
try {
photoFile = createImageFile();
Log.i("DTPI-1", "dispatchTakePictureIntent: The IF AND TRY");
} catch (IOException ex) {
Log.i("DTPI-3" , "dispatchTakePictureIntent: catch");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.i("photoURI", "dispatchTakePictureIntent: PHOTO FILE NOT EMPTY");
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//setResult(RESULT_OK, takePictureIntent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
Log.i("CIF -1", "createImageFile: Create FILE");
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;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Result", "onActivityResult: WE GET HERE");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
Error logs.
2019-05-06 20:01:33.555 23363-23363/com.example.camera E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.camera, PID: 23363
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.camera/com.example.camera.aCamera}: 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:4339)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
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.camera.aCamera.onActivityResult(aCamera.java:81)
at android.app.Activity.dispatchActivityResult(Activity.java:7235)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4335)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The camera saves the image to the photoUri that you supply in your Intent. In onActivityResult you have to get the Bitmap from that file.
The line putExtra is the issue. Delete that line and receive bitmap in
onActivityResult like mentioned below.
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
Hope this works. You will see the explaination here on a post with similar issue.
As mentioned by #aalap patel, the issue is not with onActivityResult, it is with one line in dispatchTakePictureIntent method.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
adding to this is the code that he also mentions.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have an app and I need to take photos and then upload it to firebase. I basically need Uri path of the photo taken.
I read Get file path of image on Android, but I have a problem with NullPointerException.
Main difference between my problem and the problem above is that I'm doing it in a Fragment.
Here is my code:
mTakePhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
I get NullPointerException in line with Uri imgUri.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgView.setImageBitmap(photo);
Uri imgUri = getImageUri(getActivity().getApplicationContext(), photo);
mManager.setPhotoUri(imgUri);
}
}
And here is the method I use to get Uri.
private Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
The exact error message is:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=android:fragment:1, request=22222, result=-1,
data=Intent { act=inline-data (has extras) }} to activity
{.MainActivity}:
java.lang.NullPointerException: uriString
I would appreciate any help.
The entire error log:
09-14 12:06:18.448 16497-16497/com.example.radzik.recipes E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.radzik.recipes, PID: 16497
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:1, request=22222, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.radzik.recipes/com.example.radzik.recipes.activity.MainActivity}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.(Uri.java:475)
at android.net.Uri$StringUri.(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.example.radzik.recipes.fragment.ChoosePhotoFragment.getImageUri(ChoosePhotoFragment.java:144)
at com.example.radzik.recipes.fragment.ChoosePhotoFragment.onActivityResult(ChoosePhotoFragment.java:135)
at android.app.Activity.dispatchActivityResult(Activity.java:6452)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Your problem is with getActivity() becasue you are getting the intent of the current activity you were on which will fail.
So if you move your code to the OnActivityResult this will make it work.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//first call super
super.onActivityResult(requestCode, resultCode, data);
//rest of your code
}
Don't forget to add
<uses-permission android:name="android.permission.CAMERA" />
and/or without depends on your app
<uses-feature android:name="android.hardware.camera" />
I am very sorry if this may be a question with a simple solution.
What Am I Trying To Do?
Capture an image from a Button
Upload that image to Firebase storage
Retrieve that image in an ImageView
What Is My Trouble So Far?
Takes picture, but crashes when I click the tick.
Hence nothing is being uploaded or being achieved.
My Code
P.N I have looked at lots of other forums and video tutorials but nothing seems to be working. Hopefully someone can help.
public class LeaderboardActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private static final int REQUEST_TAKE_PHOTO = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mStorage = FirebaseStorage.getInstance().getReference();
final Button bImage = (Button) findViewById(R.id.bCamera);
final ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
mProgress = new ProgressDialog(this);
bImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgress.setMessage("Uploading Image");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(LeaderboardActivity.this, "Uploading Complete...", Toast.LENGTH_LONG);
}
});
}
}
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
mCurrentPhotoPath = 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();
} 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.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
Error In Android Monitor
Not sure if this will help
02-13 02:30:32.693 2133-2133/com.example.rikhi.chores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rikhi.chores, PID: 2133
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.rikhi.chores/com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity}: 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:4089)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity.onActivityResult(LeaderboardActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I have looked at other people who had the same problem, followed what they said nothing happend, followed the Google Android instructions for this and again same problem.
On button, click remove that intent and just call your
dispatchTakePictureIntetnt() method on Onclick button Listener
Also, check go to your emulator settings, and check your camera
permission is on for your this app and also go to firebase console
and check the rules if, rules are not equal to null made them equal
to null then run your app because !=null rules only work when there
is an authentication method in your app