Fragment onActivityResult returns null - android

In the app I'm developing, the user can define an image on his profile. The first time the app is executed, an intro activity is shown where the user can choose between selecting a photo from the galery or taking a new one with the camera.
This works fine. After the user sets a profile pic, I save it in the app folder and I can use that pic inside the app later.
My app is based on the Navigation Drawer (support) so it is composed by fragments. One of this fragments is for the user's profile where the profile pic is shown. here, the user has te chance to change this pic again. An here is where I'm getting troubles.
To select a new pic, I'm using the same code I used to get the pic in the intro activity, just adapting some things to the fragment (putting getActivity()). But it seems that is not returning the image to the fragment and it's throwing a NPE.
This is how the pic is selectect from gallery in SettingsFragment:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST_FRAG);
And here is the onActivityResult in SettingsFragment too:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST_FRAG:
if (resultCode == getActivity().RESULT_OK && data != null) {
/*We get the image URI*/
Uri selectedImageUri = data.getData();
Bitmap srcBmp = null;
try {
srcBmp = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
} catch (IOException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
}
/*Transform the original image to landscape to use it as profile background*/
Bitmap landBmp = null;
if (srcBmp.getWidth() <= srcBmp.getHeight()) {
landBmp = Bitmap.createBitmap(
srcBmp,
0,
srcBmp.getHeight()/2 - srcBmp.getWidth()/2, //srcBmp.getHeight()/4 ?
srcBmp.getWidth(),
srcBmp.getWidth() /2
);
}
/*Scale the bitmap*/
int originalWidth = srcBmp.getWidth();
int originalHeight = srcBmp.getHeight();
int newWidth = 400;
int newHeight = (originalHeight*newWidth)/originalWidth;
Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
/*Save the bitmap in app-folder*/
ContextWrapper cw1 = new ContextWrapper(getActivity().getApplicationContext());
File directory1 = cw1.getDir("profile", Context.MODE_PRIVATE);
if (!directory1.exists()) {
directory1.mkdir();
}
File filepath1 = new File(directory1, "profile_pic.png");
FileOutputStream fos1 = null;
try {
fos1 = new FileOutputStream(filepath1);
fullbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos1);
fos1.close();
} catch (Exception e) {
Log.e("SAVE_FULL_IMAGE", e.getMessage(), e);
}
/*Show background profile pic*/
Drawable drawable = new BitmapDrawable(getResources(), fullbitmap);
header_container.setBackgroundDrawable(drawable);
}
break;
But as said, the app crashes an this is what logcat tells:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=-1,
data=Intent { dat=content://media/external/images/media/204 flg=0x1 }}
to activity {com.myproject.executer/com.myproject.executer.MainActivity}:
java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:3389)
Caused by: java.lang.NullPointerException at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:590)
at com.myproject.executer.SettingsFragment.onActivityResult(SettingsFragment.java:275)
Where line 275 is Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
So, I don't understand well what is happening, because it says something that is failing to deviler the result to MainActivity , and it has to deliver the result to SettingsFragment.

If the onActivityResult() method doesn't complete and return, the system counts it as the delivery having failed, which is why the errors start with that message.
In your code, it would seem that landBmp is null, because the condition srcBmp.getWidth() <= srcBmp.getHeight() is false, and you don't initialize landBmp in that case. This is throwing the NullPointerException, and halting execution before onActivityResult() returns.

you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};

Related

How can I send back the captured image taken from second activity back to the main activity?

This is my code from the main activity class named Account class wherein when I press the add entry button it will navigate to the next activity which is the AddEntry class
//ADD ENTRY BUTTON
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Account.this, AddEntry.class);
startActivityForResult(intent,REQUEST_CODE_ADD);
}
});
After it goes to the second activity which is the AddEntry class, a picture would be captured using the user's camera when the ImageView named entryPhoto is clicked
entryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempImage = null;
try {
tempImage = createImage();
} catch (Exception e) {
e.printStackTrace();
}
if (tempImage != null){
Uri uriImage = FileProvider.getUriForFile(c,"com.example.login.fileprovider",
tempImage);
mCurrentPhotoUri = uriImage;
takePhoto.putExtra(MediaStore.EXTRA_OUTPUT,uriImage);
if (ContextCompat.checkSelfPermission(c, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(AddEntry.this,
new String[]{Manifest.permission.CAMERA},
REQ_CODE_CAMERA);
}
else {
startActivityForResult(takePhoto,REQ_CODE_TAKE_PHOTO);
}
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
entryPhoto.setImageURI(mCurrentPhotoUri);
}
Here is the code where I put all the the information inputted by user then send it back to the main activity. In the addPhoto is where I am supposed to put the image to be passed. I only tried passing an image from my drawable because I really don't know how to pass the image captured.
Intent data = new Intent();
data.putExtra("addPhoto",R.drawable.anonymous);
data.putExtra("addName", entryName.getText().toString());
data.putExtra("addRemark", entryRemark.getText().toString());
data.putExtra("addBirthday", entryBirthday.getText().toString());
data.putExtra("addAddress", entryAddress.getText().toString());
data.putExtra("addGender", selectedGender);
data.putExtra("addContactNo", entryContactNo.getText().toString());
data.putExtra("addHobbies", entryHobbies.getText().toString());
data.putExtra("addOtherInfo", entryOtherInfo.getText().toString());
setResult(RESULT_OK,data);
finish();
And this is the code in the onActivityResult in the main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data); //ONACTRESULT OF ADD ENTRY
if (requestCode == REQUEST_CODE_ADD && resultCode == RESULT_OK){
int addPhoto = data.getIntExtra("addPhoto",1);
String addName = data.getStringExtra("addName");
String addRemark = data.getStringExtra("addRemark");
String addBirthday = data.getStringExtra("addBirthday");
String addAddress = data.getStringExtra("addAddress");
String addContactNo = data.getStringExtra("addContactNo");
String addGender = data.getStringExtra("addGender");
String addHobbies = data.getStringExtra("addHobbies");
String addOtherInfo = data.getStringExtra("addOtherInfo");
entryList.add(0,new Entry(addPhoto,addName,addRemark,addBirthday,addGender,addAddress,addContactNo,addHobbies,addOtherInfo));
myAdapter.notifyDataSetChanged();
}
Please I hope you will help me. I am still a beginner but I really want to be good at programming. Thank you in advance.
I think you can pass the Uri directly in bundle of Intent as it extends Parcelable which means it can retrieved as is
Adding
data.putExtra("addPhoto", mCurrentPhotoUri);
Retrieving
Uri photoUri = getIntent().getParcelableExtra<Uri>("addPhoto");

onActivityResult() is not calling in fragment

I want to scan QR Code in fragment.
But onActivityResult is not calling.
Fragment.java
#Override
public View onCreateView(LayoutInflater inflater ,ViewGroup container ,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_offer ,container ,false );
scanOffer = view.findViewById( R.id.scanOffer );
scanOffer.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBarcode();
}
} );
return view;
}
public void scanBarcode() {
/** This method will listen the button clicked passed form the fragment **/
Intent intent = new Intent(getContext(),CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
uniqueCode = data.getStringExtra("SCAN_RESULT");
Log.d(TAG, "contents: " + uniqueCode);
Toast.makeText( getContext() ,uniqueCode ,Toast.LENGTH_SHORT ).show();
// callAddStoreContestParticipantService();
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "RESULT_CANCELED");
}
}
}
Please help me.
onActivityResult() is not calling
CaptureActivity.class opens Qr after scanning onActivityResult() is not calling
Try below code for barcode scan and also override on activity result in parent activity
private static final int BARCODE_REQUEST = 312;
private void startBarcode() {
//IntentIntegrator.forFragment(getActivity().initiateScan()); // `this` is the current Fragment
IntentIntegrator integrator = new IntentIntegrator(getActivity()) {
#Override
protected void startActivityForResult(Intent intent, int code) {
Fragment.this.startActivityForResult(intent, BARCODE_REQUEST); // REQUEST_CODE override
}
};
//IntentIntegrator integrator = new IntentIntegrator(getActivity());
//IntentIntegrator.forSupportFragment(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.setOrientationLocked(false);
integrator.setTimeout(15000);
integrator.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case BARCODE_REQUEST:
IntentResult Result = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
if (Result != null) {
if (Result.getContents() == null) {
Timber.i("cancelled scan");
showSnackbar("cancelled scan", true);
} else {
Timber.i("Scanned");
showSnackbar("Code scan successfully", false);
try {
long id = Long.parseLong(Result.getContents());
// getFood(id);
searchBarcode(Result.getContents());
} catch (Exception e) {
e.printStackTrace();
}
// searchBarcode(Result.getContents());
//getFood(Long.valueOf(mItem.get(position - 1).getID()));
}
} else {
showSnackbar("Barcode not scanned", true);
Timber.i("Barcode Result is NULL");
super.onActivityResult(requestCode, resultCode, data);
}
break;
}
}
You can get reference from this example:Barcode Scanner
you have to call getActivity().startActivityForResult(intent, 0);
in your fragment
and in your activity you in onActivityResultMethod() you have to call yourfragmnt.onActivityResult()

Android Camera passing bitmap from Camera Intent to MainActivity

I am trying to take a picture and set it in my MainActivity to an ImageView.
I want to have my camera activity as a seperate class so i tried the following:
MainActivity:
public void onClick(View v) {
switch (v.getId()) {
case R.id.action_button:
Intent camera = new Intent(MainActivity.this,Camera.class);
startActivityForResult(camera ,CAMERA_IDENTIFITER);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","Sucessfully callbacked!"); //This one wont be executed!
switch(requestCode) {
case (CAMERA_IDENTIFITER) : {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
mImageView.setImageBitmap(bitmap);
}
break;
}
}
}
And this is my camera Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
pm = getPackageManager();
}
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult){
dispatchTakePictureIntent();
}
}
public void dispatchTakePictureIntent() {
if (takePictureIntent.resolveActivity(pm) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch {...}
if (photoFile != null) {
pictureTaken = true;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
Log.d("onActivityResult","finish() executed!"); //This one gets executed!
finish();
} catch {...}
}
}
The camera intent is starting properly but when i take a picture i dont get back to the onActivityResult in my MainActivity , i'm stuck in the Camera intent.
Your onStart() gets called after onActivityResult() is being executed. Hence starting camera intent again and again. Put Logs and test your self.
To solve the issue
Keep a boolean variable in your activity isFronActivityResult. Keep default value as false and do isFromActivityResult = true; inside onActivityResult(). In onStart do the following:
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult)
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
isFromActivityResult = true;// add this line
finish();
} catch {...}
}
}

onActivityResult data always returns null inside fragment

gallery.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class gallery extends Fragment {
private static final int PICK_FROM_GALLERY = 1;
RelativeLayout gallerylayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainfragment, container, false);
gallerylayout = (RelativeLayout) v.findViewById(R.id.gallery_layout);
gallerylayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fireGallery();
}
});
return v;
}
private void fireGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_GALLERY:
String[] all_path = data.getStringArrayExtra("all_path");
System.out.println("all_path " + all_path); //Returns null
System.out.println("Data " + data.getExtras()); //Returns null
break;
}
}
}
The data in onActivityResult is always null, please correct me if anything wrong with my code. As mentioned both logs inside onActivityResult returns null. Note i am extending Fragment not activity.
Try this, you may get data from it:
#Override
protected void onActivityResult (int requestCode,int resultCode,Intent data){
super.onActivityResult (requestCode,resultCode,data);
try{
// When an Image is picked
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
&& null != data){
// Get the Image from data
Uri selectedImage = data.getData ();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver ().query (selectedImage,
filePathColumn,null,null,null);
// Move to first row
cursor.moveToFirst ();
int columnIndex = cursor.getColumnIndex (filePathColumn[0]);
String imgDecodableString = cursor.getString (columnIndex);
cursor.close ();
Log.e ("Image Path",imgDecodableString);
Toast.makeText (this,"You have picked Image" ,
Toast.LENGTH_LONG).show ();
}
else{
Toast.makeText (this,"You haven't picked Image",
Toast.LENGTH_LONG).show ();
}
}
catch (Exception e){
Toast.makeText (this,"Something went wrong",Toast.LENGTH_LONG)
.show ();
Log.e ("Exception",e.toString ());
}
}
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};
if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK && null!=data)
{
Bitmap photo;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
if (picturePath != null) {
Log.v("", picturePath);
cursor.close();
photo = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
photo = Bitmap.createScaledBitmap(photo, 1200, 1200, true);
this.data = baos.toByteArray();
chooseImage.setImageBitmap(photo);
}
else {
Utilities.showToast(getActivity(),
"This image is not on your device");
}
}
if You want to get picture from the gallery then you should use this function

Null pointer exception when calling startActivityForResult()

I'm having a problem (Null Pointer Exception) when calling startActivityForResult() from class inside another class, here is the code :
public class OCRActivity extends Activity {
public OCRActivity(String operator)
{
this.operator = operator;
}
public void startCameraActivity() {
final Intent capture_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(capture_intent, 1); // I get the Null pointer Exception here
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == 1){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
}
}
and here is where I call startCameraActivity()
public class WayToFillActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.way_to_fill);
CAMERA_BTN = (Button) findViewById(R.id.camera_btn);
CAMERA_BTN.setOnClickListener(this);
Intent operator_intent = getIntent();
OPERATOR = operator_intent.getStringExtra("operator");
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.camera_btn)
{
OCRActivity ocr = new OCRActivity(OPERATOR);
ocr.startCameraActivity();
}
}
So please tell me if I'm doing something wrong !!
The Logcat
01-13 16:22:26.583: E/AndroidRuntime(32425): java.lang.NullPointerException
01-13 16:22:26.583: E/AndroidRuntime(32425): at android.app.Activity.startActivityForResult(Activity.java:3190)
01-13 16:22:26.583: E/AndroidRuntime(32425): at com.almannaa.EasyRecharge.OCRActivity.startCameraActivity(OCRActivity.java:176)
You are treating OCRActivity as an ordinary Java class, and not like another Activity. Due to this, when you call startActivityForResult() you get a NPE as the Activity's onCreate() has not been called, which means that its current instance is not valid for calling startActivityForResult()
Instead, try using:
public class WayToFillActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.way_to_fill);
CAMERA_BTN = (Button) findViewById(R.id.camera_btn);
CAMERA_BTN.setOnClickListener(this);
Intent operator_intent = getIntent();
OPERATOR = operator_intent.getStringExtra("operator");
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.camera_btn)
{
OCRActivity ocr = new OCRActivity(OPERATOR);
ocr.startCameraActivity();
}
}
public void startCameraActivity() {
final Intent capture_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(capture_intent, 1); // I get the Null pointer Exception here
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == 1){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
}
}
}
You should probably move functions like performCrop() (and any other functions that don't really need to be in the activity itself, and can work by receiving data as parameters and returning it) into a separate class (call it Utility or whatever).
Maybe you should check if the data is not null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && data != null) {
if(resultCode == RESULT_OK){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
} }

Categories

Resources