Watson Visual Recognition in Android - java

I am developing an app in which my requirement to select an image from the SD card and send in to IBM Waston Visual Recognition service to identify the content in the image. I am doing like this..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == MainActivity.this.RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = MainActivity.this.getContentResolver().query(selectedImage,filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
analizarImagen(picturePath);
}
}
private void analizarImagen(String path){
File image = new File(path);
System.out.println(path);
VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
service.setApiKey("api-key");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder()
.images(image)
.build();
VisualClassification result = service.classify(options).execute();
System.out.println(result.toString());
}
But when I select an image, the application crashes
Error:
02-02 03:43:49.720 3355-3355/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/23 }} to activity {com.cucea.mauricio.visual/com.cucea.mauricio.visual.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
at android.app.ActivityThread.access$1100(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:179)
at com.cucea.mauricio.visual.MainActivity.analizarImagen(MainActivity.java:84)
at com.cucea.mauricio.visual.MainActivity.onActivityResult(MainActivity.java:68)
at android.app.Activity.dispatchActivityResult(Activity.java:5192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184) 
at android.app.ActivityThread.access$1100(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 

You are hitting server from main(UI) thread which is not allowed in android. Call your analizarImagen() method in separate thread or async task.
Check this document:
https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Related

App crashes when calling dispatchTakePictureIntent

My app is crashing when I click on the following button to use dispatchTakePictureIntent
My code:
ic_img_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent(PHOTO);
}
});
private void dispatchTakePictureIntent(int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP);
takePictureIntent.putExtra("return-data", true);
startActivityForResult(takePictureIntent, requestCode);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 2;
Bitmap bitmap = RotateBitmap(BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(PHOTO_TEMP), null, bmOptions), getPictureOrientation(PHOTO_TEMP));
thumb = getThumbnail(bitmap);
setThumbnail(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Log:
--------- beginning of crash
2020-09-10 17:41:31.769 25093-25093/ubisolutions.net.datacenterinventory.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: ubisolutions.net.datacenterinventory.debug, PID: 25093
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3782)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:615)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3653)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3774)
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
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:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) 
2020-09-10 17:41:31.775 1239-1239/? E/NotificationService: Suppressing notification from package by user request.
2020-09-10 17:41:31.775 1239-25274/? I/QCALOG: [MessageQ_Client] connecting to server [/data/misc/location/mq/location-mq-s]
2020-09-10 17:41:31.776 1239-25274/? E/QCALOG: [MessageQ_Client] connect error: 111, [Connection refused]
I have seen some responses about similar issues but none of them helped me to solve it.
thanks.
Your code line
takePictureIntent.putExtra("return-data", true);
requests, that the picture data is returned directly, but it is too large to be passed back in the result. You should instead get it from PHOTO_TMP you are passing in the intent too.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP)

onActivityResult should call super.onActivityResult

I am new to Android Studio and trying to create a simple app. The app keeps crashing, when I need to save the data from the other activities, using onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Job updatedJobDetails = (Job)data.getSerializableExtra("updatedJobDetails");
int position = data.getIntExtra("pos", -1);
adapter.remove(adapter.getItem(position));
adapter.insert(updatedJobDetails, position);
}
}
}
First it says, that I need to
onActivityResult should call super.onActivityResult
but when I do that, it crashes as soon as I use the method. Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.smapassignment01, PID: 6809
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.smapassignment01/com.example.smapassignment01.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=15; index=-1
at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
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:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=15; index=-1
at java.util.ArrayList.get(ArrayList.java:439)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:393)
at com.example.smapassignment01.MainActivity.onActivityResult(MainActivity.java:122)
at android.app.Activity.dispatchActivityResult(Activity.java:7454)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402) 
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:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
I/Process: Sending signal. PID: 6809 SIG: 9
Process 6809 terminated.
I can't really read from the logcat-report, what I've done wrong.
According to this SO-question it is because of getAdapterPosition - but I don't even use it, so I'm completely lost and have now used several hours, stuck.
UPDATE:
Just to show, that my pos has been sat in the other activity, from where the app crashes:
btnSaveNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
job.setUserNotes(etJobNotes.getText().toString());
if (!cbAppliedJob.isChecked()){
job.setJobApplied(false);
}
else{
job.setJobApplied(true);
}
Intent data = new Intent();
position = getIntent().getIntExtra("pos", -1);
data.putExtra("pos", position);
data.putExtra("updatedJobDetails", job);
setResult(RESULT_OK, data);
finish();
}
});

IllegalStateException: Can not perform this action after onSaveInstanceState with onActivityResult

I am new to Android development. I got an issue. I tried the last couple of hour but I can't figure out this. if so I got a popular question. IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager but failed because of the lack of Android development experience.
Here is code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
MyCustomDialogFragment newPopup = new MyCustomDialogFragment();
newPopup.setMyClickListener(MainActivity.this);
FragmentManager fragmentManager = getSupportFragmentManager();
newPopup.show(fragmentManager, "CashReceivePopup");
}
}
}
Here is the error:
01-04 05:08:57.010 13609-13609/com.nazmul.aznazgame.bitlife
D/AndroidRuntime: Shutting down VM 01-04 05:08:57.068
13609-13609/com.nazmul.aznazgame.bitlife E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.nazmul.aznazgame.bitlife, PID: 13609
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=4, result=-1, data=Intent { (has extras)
}} to activity
{com.nazmul.aznazgame.bitlife/com.nazmul.aznazgame.bitlife.MainActivity}:
java.lang.IllegalStateException: Can not perform this action after
onSaveInstanceState
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:2053)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2079)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:678)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:632)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
at com.nazmul.aznazgame.bitlife.MainActivity.showEducationDialog(MainActivity.java:1716)
at com.nazmul.aznazgame.bitlife.MainActivity.manageActivity(MainActivity.java:604)
at com.nazmul.aznazgame.bitlife.MainActivity.onActivityResult(MainActivity.java:580)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617) 
at android.app.ActivityThread.access$1300(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  01-04
05:08:59.825 13609-13651/com.nazmul.aznazgame.bitlife
I/CrashlyticsCore: Crashlytics report upload complete:
5C2EEA4F018E-0001-3529-63E978D09744 01-04 05:08:59.955
13609-13609/com.nazmul.aznazgame.bitlife I/Process: Sending signal.
PID: 13609 SIG: 9
You must call super.onActivityResult(requestCode, resultCode, data) before doing any FragmentTransactions in your onActivityResult() method as that call is what 'unlocks' the FragmentManager and notes that you are in a valid state to do FragmentTransactions.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Add this line
super.onActivityResult(requestCode, resultCode, data);
// This all remains the same
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
MyCustomDialogFragment newPopup = new MyCustomDialogFragment();
newPopup.setMyClickListener(MainActivity.this);
FragmentManager fragmentManager = getSupportFragmentManager();
newPopup.show(fragmentManager, "CashReceivePopup");
}
}
}
It is a common problem. You have 2 options how to deal with this issue.
you can override the show() method and put its content inside a try-catch block
You display the dialog in the followong way
FragmentManager fm = getSupportFragmentManager();
MyDialog d = new MyDialog();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(d, "dialog");
ft.commitAllowingStateLoss();

Android get file path of image with in Fragment [duplicate]

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" />

NullPointerException when I try to capture an image (built-in camera) and save it to a file [duplicate]

This question already has answers here:
Android Camera : data intent returns null
(11 answers)
Closed 8 years ago.
Here's what the app does - User clicks button (to take a picture) on Activity A, the captured image gets set as on an ImageView in Activity A, and then the user clicks a "save" button, which takes him/her to Activity B, where the image they took gets displayed (on an ImageView in Activity B)
In order to do this I am trying to find a way to save the image. I tried many different things, but I keep getting a NullPointerException. Here is my code:
I highlighted the area where I think the error is:
public void onClick(View view) {
switch (view.getId()) {
case R.id.take_picture_button:
takePic = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(); //so photoFile = the file we created up top
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
**takePic.putExtra(MediaStore.EXTRA_OUTPUT**, //extra_output is just the name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
**Uri.fromFile(photoFile));**
startActivityForResult(takePic, cameraData);
}
And here is the code for the onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == cameraData && resultCode == RESULT_OK) {
mReturningWithResult = true;
extras = data.getExtras();
And here is where I set my image view to my captured image (on Activity A)
#Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
foodImage = (Bitmap) extras.get("data");
foodImageView.setImageBitmap(foodImage);
}
mReturningWithResult = false;//resetting it for next time
}
Here is the logcat (sorry I'm new to this)
10-15 20:58:59.612 32005-32005/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
10-15 20:59:21.545 32005-32005/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:23.127 32005-32005/com.example.nikhil.foodshark W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark D/AndroidRuntime﹕ Shutting down VM
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41a39da0)
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nikhil.foodshark, PID: 32005
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.nikhil.foodshark/com.example.nikhil.foodshark.NewDish}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1400(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.nikhil.foodshark.NewDish.onActivityResult(NewDish.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:5650)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
            at android.app.ActivityThread.access$1400(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
10-15 20:59:56.353 32005-32005/com.example.nikhil.foodshark I/Process﹕ Sending signal. PID: 32005 SIG: 9
10-15 20:59:56.613 378-378/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:56.723 378-378/com.example.nikhil.foodshark I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050__release_AU ()
OpenGL ES Shader Compiler Version: 17.01.12.SPL
Build Date: 03/28/14 Fri
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050
Local Patches: NONE
Reconstruct Branch: NOTHING
10-15 20:59:56.763 378-378/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
Do you guys know a way I can fix this? Thank you!
You are passing MediaStore.EXTRA_OUTPUT, in which case, the intent field in onActivityResult can be null.
The solution is to just use the photo file you created, and passed as uri in the putExtra
So instead of trying to get the photo file location from the intent, just use Uri.fromFile(photoFile)
replace
extras = data.getExtras();
...
with
`Uri.fromFile(photoFile)`
or just use photoFile if that is what you want...just dont rely on intent data

Categories

Resources