Capture Image, Upload To Firebase And Retrieve Java Android Studio - java

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

Related

Storage Access Framework - failing to obtain document tree from uri (returned from Drive app)

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

data null onActivityResult

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.

‘Failure delivering result ResultInfo’ once then works normally after crash [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I had to update my app to work along with the new android versions, targeting the N version, I Updated:
from:
Uri.fromFile();
to:
FileProvider.getUriForFile();
I did this as follows:
Based on: ( android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData() )
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities=" com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
provider_paths:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="external_files" path="."/>
</paths>
FntTakePicture:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
//......
//......
btnTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
outputFileName = null;
try {
/*if(fragmentPosition == 0 || fragmentPosition == 4)
outputFileName = Images.createImageFile2();//PNG
else
outputFileName = Images.createImageFile3();//JPG*/
outputFileName = Images.createImageFile3();
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(outputFileName));
Uri photoURI = FileProvider.getUriForFile(getContext(),"com.mydomain.fileprovider",outputFileName);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, RC_IMAGE_CAPTURE);
} catch (IOException e) {
e.printStackTrace();
FirebaseCrash.report(e);
}
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_IMAGE_CAPTURE && resultCode == RESULT_OK) {
loadImage(outputFileName.getAbsolutePath());//outputFileName.getAbsolutePath()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
txtInstructions.setText(Html.fromHtml(
String.format(
getResources().getString(R.string.validate_picture2),
defaultValidateText
),Html.FROM_HTML_MODE_LEGACY
));
} else {
txtInstructions.setText(Html.fromHtml(
String.format(
getResources().getString(R.string.validate_picture2),
defaultValidateText
)), TextView.BufferType.SPANNABLE);
}
btnTakePicture.setText(getString(R.string.take_photo_again));
//this.data.setImage(Images.compressImage(picture),fragmentPosition);
this.data.setImage(outputFileName.getAbsolutePath(),fragmentPosition);
Log.e("Data Picture"," Vin: "+this.data.getVin()+" lon: "+this.data.getLon()+ " lat: "+this.data.getLat());
if(lastPage)
validateContinueBoton();
listener.save(this.data);
}
}
public void loadImage(final String path){
new AsyncTask<Void,Void,Bitmap>(){
#Override
protected Bitmap doInBackground(Void... params) {
return Images.decodeSampledBitmapFromFile(path,
getResources().getDimensionPixelSize(R.dimen.ancho_default)/2);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imgPictureTaken.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgPictureTaken.setImageBitmap(bitmap);
}
}.execute(null,null,null);
}
Images Class:
public class Images{
static File createImageFile3() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(new Date());
String imageFileName = "NTS_Image_" + timeStamp + "_";
File storageDir = ContextCompat.getExternalCacheDirs(App.getContext())[0];
File nf = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
nf.deleteOnExit();
return nf;
}
}
Also, this event is in a fragment, I don't know if that's matters.
After run install app give it permissions then crash once it works normally…
The exception I got it this:
04-17 15:00:10.058 669-669/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
04-17 15:00:10.202 13596-13596/com.mydomain E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mydomain, PID: 13596
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=74538, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.mydomain/com.mydomain.CaptureWizard}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getAbsolutePath()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4094)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4137)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1529)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getAbsolutePath()' on a null object reference
at com.mydomain.FntTakePicture.onActivityResult(FntTakePicture.java:201)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at com.mydomain.CaptureWizard.onActivityResult(CaptureWizard.java:133)
at android.app.Activity.dispatchActivityResult(Activity.java:6931)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4090)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4137)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1529)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Make sure that you are saving outputFileName in your saved instance state Bundle. Your process may be terminated while your app is in the background, which would cause that field to become null by default in your new process.

After calling startActivityForResult() subsequent code still runs

So basically I want the app to: after pressing a button opens the gallery, the user selects one image and after that saves the uri in a variable. That's all it needs to do but what I found is that after calling startActivityForResult() subsequent code still runs in the background creating a NullPointerException error, since the variable I wanted has not yet been retrieved from the intent.
public class MainActivity extends AppCompatActivity {
final static int PICK_IMAGE_REQUEST = 1;
private String imageUriStr;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = this.getSharedPreferences("MyPreferences",MODE_PRIVATE);
ImageView addImgButton = (ImageView) findViewById(R.id.add_img_button);
addImgButton.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"), PICK_IMAGE_REQUEST);
if (prefs.contains(imageUriStr)) {
imageUriStr = prefs.getString("imageUriStr", ""); //Get the data from prefs
}
Log.d("Value",imageUriStr); //verify if it is correct
prefs.edit().clear();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUriStr = data.getData().toString(); //convert to string to use it with SharedPreferences
prefs.edit().putString("imageUriStr",imageUriStr).apply();
}
}
}
One solution would be to do everything inside the onActivityresult, but I also want to later user another intent to crop the image based on that uri, but I think an Intent inside an onActivityresult will be too messy or is it acceptable? I guess I'm missing something.
Keeping with my code will generate this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.prototypeapp, PID: 17826
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:154)
at com.example.android.prototypeapp.MainActivity$1$override.onClick(MainActivity.java:41)
at com.example.android.prototypeapp.MainActivity$1$override.access$dispatch(MainActivity.java)
at com.example.android.prototypeapp.MainActivity$1.onClick(MainActivity.java:0)
at android.view.View.performClick(View.java:5264)
at android.view.View$PerformClick.run(View.java:21297)
at android.os.Handler.handleCallback(Handler.java:743)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Your private String imageUriStr; is null.Since it is null you are getting null pointer exception. Assign it with the empty string like : private String imageUriStr = "";.
AND
Check in shared preference like :
if(prefs.contains("imageUriStr"))
Your Code is crashing on this line:
Log.d("Value",imageUriStr);
Reason: imageUriStr value is null and a valid message is required to print the log
You can either use Log as :
Log.d("Value","Image URI Value: "+imageUriStr);
or you can put your Log inside if block like:
if (prefs.contains(imageUriStr)) {
imageUriStr = prefs.getString("imageUriStr", "");//Get the data from prefs
Log.d("Value",imageUriStr); //verify if it is correct
}

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException even when file IS actually there

I'm creating a simple app to take a picture. this is my code
Button b1;
ImageView iv;
String TAG = "MAIN ACTIVITY";
File photo;
private Uri mImageUri;
private File createTemporaryFile(String part, String ext) throws Exception {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File tempDir = new File(externalStorageDirectory + "/cameratest/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(getApplicationContext(), "Please check SD card! Image shot is impossible!",
Toast.LENGTH_SHORT).show();
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG, mImageUri.toString());
Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.toString());
iv.setImageBitmap(bitmap);
}
}
as you can see i've added eLog.d(TAG, mImageUri.toString()); at the end and in the logcat (as well as the FileNotFoundException) i see this direcory:
03-27 00:43:30.498 30526-30526/myapplication.example.falcoleo.cameratest1 D/MAIN ACTIVITY: file:///storage/emulated/0/cameratest/picture459838058.jpg
03-27 00:43:30.499 30526-30526/myapplication.example.falcoleo.cameratest1 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/cameratest/picture459838058.jpg: open failed: ENOENT (No such file or directory)
guess if this directory exists?
spoler alert, it does. And it's not like the image is created after the BitmapFactory.decodeFile. I really do not understand what i'm doing wrong. Everything works fine except when it actually has to display the photo, then it just does not display it. just blank. Like WTF m8 i'm just trying to do my job no need to go crazy, you know.
Replace mImageUri.toString() with mImageUri.getPath().
decodeFile expects a path, not an uri string.
file:///storage/emulated/0/cameratest/picture459838058.jpg
Remove file:// because the decodeFile() expects a file system path.
/storage/emulated/0/cameratest/picture459838058.jpg
Use BitmapFactory.decodeStream instead of BitmapFactory.decodeFile.
try ( InputStream is = new URL( file_url ).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
}
Source https://stackoverflow.com/a/28395036/5714364
Ok for me it was the file path was wrong so I needed to get the real filepath.
First
File file = new File(getPath(uri));
public String getPath (Uri uri)
{
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (cursor == null)
return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
Then Back To Uri
Uri newUri = Uri.fromFile(file);
This conversion to file and back to uri did the trick for me. I was receiving simple data from action.SEND.

Categories

Resources