Null pointer exception when calling startActivityForResult() - android

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

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");

Image taken from gallery doesn't appear

I use Picasso to get an image from the gallery and set it to an ImageView, but it does not do it. Couldn't find a problem. What is the reason? And the interesting thing is that there was no error. I tested the program through my own device.
public class MainActivity extends AppCompatActivity {
String imageUri ;
ImageView img ;
private static final int GALLERY_REQUEST = 9391;
Button b ;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
imageUri = data.getData().toString() ;
loadImage() ;
}
else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void loadImage() {
Picasso.with(this).load(imageUri).fit().centerInside().into(img);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.image);
b = (Button)findViewById(R.id.button) ; // it is button used to open //a gallery
}
//thins function called when button pressed
public void openGallery(View view) {
Intent i = new Intent(ACTION_PICK,EXTERNAL_CONTENT_URI) ;
startActivityForResult(i,GALLERY_REQUEST);
}
}
You called super.onActivityResult(requestCode, resultCode, data); which is wrong .
Do this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
Uri selectedImageURI = data.getData();
Picasso.with(this).load(selectedImageURI).fit().centerInside().into(img);
}
else
{
// handle this case
}
}
Problem Solved.
I forgot to add permission used to read external storage.

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 {...}
}
}

onCreate and onRestoreInstanceState(Bundle) not called after startActivityForResult

I'm trying to load an image from gallery.
This is the onCreate() :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_picture);
mThis = this;
mImageCache = new TakingPictureActivityCacheMngr(this);
initUi();
if (savedInstanceState == null) {
openGallery();
}
}
Here is the onSaveInstanceState():
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", mFileUri);
if (com.isee.spot.toolkit.Config.IS_DEBUG) {
Log.d(TAG, "Instance was saved.");
}
}
On restore : (never called)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file Uri
mFileUri = savedInstanceState.getParcelable("file_uri");
}
The onCreate() is never called after opening the gallery, onDestroy() is called right when the gallery is opened and so it the onSaveInstanceState().
Here is the activity declaration in the manifest :
<activity
android:name=".GalleryPictureActivity"
android:configChanges="orientation|keyboard|keyboardHidden"
android:screenOrientation="portrait" >
</activity>
I overloaded the onActivityResult() :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is loading image from gallery
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
...
Here is the answer,
The activity itself was correct.
The problem is with the activity which start it, I used : galleryPic.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Apparently this cause the onActivityResult(int, int, Intent) not be called.
Leaving this just for the chance of someone getting same behavior.
Thank you for trying to help, I guess you had no chance.
I may not be understanding the context of this code properly, but it looks like this is a custom image picking class ? You may be aware - but perhaps not - that there are built in SDK methods for this... see below:
private void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_PICK_IMAGE);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Log.v(TAG, "User Picked An Image");
handleImage(data.getData());
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.v(TAG, "User Cancelled Pick Image");
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void handleImage(final Uri selectedImage) {
String filePath = selectedImage.getEncodedPath();
Log.v(TAG, " -- picked image is " + filePath);
MyImageView.setImage(selectedImage);
}

Can i pass uri value from onActivityResult() to onClick()?

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView01 = (SurfaceView) findViewById(R.id.mSurfaceView1);
mSurfaceHolder01 = mSurfaceView01.getHolder();
mSurfaceHolder01.addCallback(EX10_04.this);
mButton02 = (Button)findViewById(R.id.buttonObj);
mButton02.setOnClickListener( new Button.OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType("audio/*");
Intent destIntent = Intent.createChooser( intent, "select audio" ); //pick up an audio file
startActivityForResult( destIntent, 0 );
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == RESULT_OK )
{
Uri uri = data.getData();
if( uri != null )
{
DrawO();//It will draw a circle
}
else
{
e.printStackTrace();
}
}
The circle not show.....
but when i put the DrawO() next to
mSurfaceHolder01.addCallback(EX10_04.this);
It draw a circle !
if i want to draw a circle in the onActivityResult event
what shuld i do ?
or if i can pass uri to onClick function ?
public void DrawO()
{
Canvas mCanvas01 = mSurfaceHolder01.lockCanvas(null);
mCanvas01.drawColor(getResources().getColor(R.drawable.white));
Paint mPaint01 = new Paint();
mPaint01.setStyle(Paint.Style.FILL);
mPaint01.setColor(getResources().getColor(R.drawable.red));
mPaint01.setStrokeWidth(1.0F);
........
.......
}
1) The circle is not drawn because the surface is not created yet. Try something like this:
boolean needDrawing = false;
public void onResume() {
if (needDrawing) {
Draw0();
needDrawing = false;
}
...
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == RESULT_OK )
{
Uri uri = data.getData();
if( uri != null )
{
needDrawing = true;//It asks to draw a circle
}
else
{
e.printStackTrace();
}
}
2) To pass the URI simply declare a field URI and assign it in onActivityResult and in onClick() check if not null, use it and invalidate it

Categories

Resources