Android Fragment onactivity result null pointer exception - java

I am android beginner, my aim is select image and display on my ImageView, I use below code but in fragment onActivity result return null pointer exception.
This is my fragmentA.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == getActivity().RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
Log.v("imageUri", imageUri.toString());
final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
initImage();
break;
}
}
I used below code for call gallery intent
image.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if( Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT )
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent.createChooser(intent,"Select Picture"), SELECT_PHOTO);
}
else
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
This is my error report ..
java.lang.RuntimeException: Unable to resume activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/images/media/506 }} to activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.NullPointerException
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/images/media/506 }} to activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.caneda.citycenter.myaccount.FragmentTabProfile.onActivityResult(FragmentTabProfile.java:217)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:163)
at com.caneda.citycenter.myaccount.AccountMainActivity.onActivityResult(AccountMainActivity.java:102)
at android.app.Activity.dispatchActivityResult(Activity.java:5305)

I think the line
resultCode == getActivity().RESULT_OK
is causing the problem
USE
resultCode == Activity.RESULT_OK
because RESULT_OK is static
However you can debug to test which code is causing NullPointerException

Actully answer is really silly, I have initialize
conditional based
if(saveInstaceState == null) { ivUpload = (ImageView) }
It should be outside of condition.
That's why it cause nullPointerException by ivUpload.
Thanks you so much for you support.

Related

Get data from intent in method of crop library

This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
((ImageView) findViewById(R.id.quick_start_cropped_image)).setImageURI(result.getUri());
Toast.makeText(
this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG)
.show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
When I take a picture my app crashes. The exception on my phone is:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=203, result=-1, data=Intent { act=inline-
data (has extras) }} to activity
{com.example.michael.matcalc/com.example.michael.matcalc.Crop}:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri
com.theartofdev.edmodo.cropper.CropImage$ActivityResult.getUri()' on a
null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4355)
...
I think that something goes wrong with the data. It crashes at this line:
((ImageView) findViewById(R.id.quick_start_cropped_image)).setImageURI(result.getUri());
The library I use is this: https://github.com/ArthurHub/Android-Image-Cropper
I would appreciate if somebody could help me.
This is because you're incorrectly using the library. You need to use the following code:
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
instead of:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
It is because when you're calling Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); you're not specifically tell the Crop library to handle the image.

Cant get image bundle data in onActivityResult

My Intent activity starting code to open camera is as follow
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
getActivity().startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Note:- This functionality is in a class extending dialogfragment class
My OnActivityResult method,which is in the Activity class,is as follows
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("sdf",""+data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
mimageView = (ImageView) findViewById(R.id.profileimageView4);
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//mimageView.setImageBitmap(imageBitmap);
}
}
The error showing in the log is as follows
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://media/external/images/media/22615 flg=0x1 }} to activity {www.vyrazu.com.purpleknights/www.vyrazu.com.purpleknights.Profile}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
What is the problem in this code.Thanks everyone for your time.
From what I can see, your code appears to be fine. However, it relies on ACTION_IMAGE_CAPTURE, and many camera apps have bugs. You might wish to try your app with a different camera app and see what the results are.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()'

I am Trying To upload image to server from gallery and camera.When i Choose image from gallery to upload to server its Work Perfactly.But when i Select camera captured Image for upload to server Its Crash And Showing the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
At OnActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
decodeFile(picturePath);
new ImageUploadTask().execute();
}else {
Toast.makeText(getApplicationContext(), "User Canceled",
Toast.LENGTH_LONG).show();
}
}
i got the error on this line in onActivityResult
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
The method i used for open camera on button click.
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
}
})
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Help Me solve this problem.I don't know How t get this error even after i used is already in my Previous PROJECT.
THANKS in Advance
I had same issue when working with Camera api and Intent of onActivityResult, finally I found out it depends on your android device version, in Android M (Marshmallow - 6.0–6.0.1 ) onActivityResult intent is like below :
requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065 564.jpg typ=image/jpeg } RESULT_OK : -1
and for android versions lower than Marshmallow:
requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1
I think you must check android version onActivityResult and the for android versions Marshmallow to get direct file from path in the Uri and Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){
final Uri data = intent.getData();
final File file = new File(data.getPath());
// now you can upload your image file
}else{
// in android version lower than M your method must work
}
I hope it can be useful for you.
if (null != account.getPhotoUrl()) {
// Write code here
}
I meet this problem either, after many test, I found its because I set the attribute named android:windowIsTranslucent=true, if I delete this attribute from style, it always work.

println needs a message - onActivityResult

I am trying to send message from my SecondActivity to FirstActivity to be printed. I am using startActivityForResult(intent, requestcode) to start the SecondActivity and then enter text and send the entered text to be displayed by FirstActivity using onActivityResult(). When I run the Activity and click on send I am getting error stating "println needs a message". The result is not getting delivered to the FirstActivity.
Below is the code:
FirstActivity:
private void StartSecondActivity() {
Log.i(tag, "SecondActivity");
Intent iSecond = new Intent(this, SecondActivity.class);
startActivityForResult(iSecond, REQUEST_CODE);
}
SecondActivity:
private void eClicked() {
Log.i(tag, "Clicked()");
String mes = mEditText.getText().toString();
Intent intent = new Intent();
intent.putExtra(EXTRA_MESSAGE, mes);
setResult(RESULT_OK, intent);
Log.i(tag, mes);
finish();
}
Here it does log correct message.
FirstActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(tag, "onActivityResult()");
if(requestCode == REQUEST_CODE ){
if(resultCode == RESULT_OK){
Intent inte = getIntent();
String m = inte.getStringExtra(SecondActivity.EXTRA_MESSAGE);
mTextView.setText(m);
}
}
}
It enters the onActivityResult and logs the message and then crashes with the below error message.
Error Message:
02-09 18:52:42.010: E/AndroidRuntime(1831): FATAL EXCEPTION: main
02-09 18:52:42.010: E/AndroidRuntime(1831): Process: droid.intentexp.intents, PID: 1831
02-09 18:52:42.010: E/AndroidRuntime(1831): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {droid.intentexp.intents/droid.intentexp.intents.FirstActivity}: java.lang.NullPointerException: println needs a message
I am not sure what is going wrong. Can someone please shed some light.
Thanks.
You should use data intent NOT getIntent()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(tag, "onActivityResult()");
if (requestCode == REQUEST_CODE ) {
if (resultCode == RESULT_OK) {
String m = data.getStringExtra(SecondActivity.EXTRA_MESSAGE);
mTextView.setText(m);
}
}
}
initialize th string m with appropriate content.
String m= " ";

Open gallery app from Android Intent

I'm looking for a way to open the Android gallery application from an intent.
I do not want to return a picture, but rather just open the gallery to allow the user to use it as if they selected it from the launcher (View pictures/folders).
I have tried to do the following:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
However this is causing the application to close once I select a picture (I know this is because of the ACTION_GET_CONTENT), but I need to just open the gallery.
Any help would be great.
Thanks
This is what you need:
ACTION_VIEW
Change your code to:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I hope this will help you. This code works for me.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
ResultCode is used for updating the selected image to Gallery View
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
return; // no cursor or no record. DO YOUR ERROR HANDLING
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) // no column index
return; // DO YOUR ERROR HANDLING
String picturePath = cursor.getString(columnIndex);
cursor.close(); // close cursor
photo = decodeFilePath(picturePath.toString());
List<Bitmap> bitmap = new ArrayList<Bitmap>();
bitmap.add(photo);
ImageAdapter imageAdapter = new ImageAdapter(
AddIncidentScreen.this, bitmap);
imageAdapter.notifyDataSetChanged();
newTagImage.setAdapter(imageAdapter);
}
You can open gallery using following intent:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Tested on Android 4.0+
Following can be used in Activity or Fragment.
private File mCurrentPhoto;
Add permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
Add Intents to open "image-selector" and "photo-capture"
//A system-based view to select photos.
private void dispatchPhotoSelectionIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.startActivityForResult(galleryIntent, REQUEST_IMAGE_SELECTOR);
}
//Open system camera application to capture a photo.
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(App.Instance.getPackageManager()) != null) {
try {
createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (mCurrentPhoto != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Add handling when getting photo.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_SELECTOR:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = App.Instance.getContentResolver().query(data.getData(), filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
mCurrentPhoto = null;
break;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) { // no column index
mCurrentPhoto = null;
break;
}
mCurrentPhoto = new File(cursor.getString(columnIndex));
cursor.close();
} else {
mCurrentPhoto = null;
}
break;
case REQUEST_IMAGE_CAPTURE:
if (resultCode != Activity.RESULT_OK) {
mCurrentPhoto = null;
}
break;
}
if (mCurrentPhoto != null) {
ImageView imageView = (ImageView) [parent].findViewById(R.id.loaded_iv);
Picasso.with(App.Instance).load(mCurrentPhoto).into(imageView);
}
super.onActivityResult(requestCode, resultCode, data);
}
As you don't want a result to return, try following simple code.
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivity(i);
if somebody still getting the error, even after adding the following code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
then you might be opening the intent in another class (by calling) due to this the app will crash when you click the button.
SOLUTION FOR THE PROBLEM
Put intent in the class file which is connected to the button's layout file.
for example- activity_main.xml contains the button and it is connected to MainActivity.java file. but due to fragmentation, you are defining the intent in some other class(lets says Activity.java) then your app will crash unless you place the intent in MainActivity.java file. I was getting this error and it is resolved by this.

Categories