Mostafa Abbas Mostafa Abbas - 3 months ago 13
Android Question

App Crash :ACTION_IMAGE_CAPTURE issue with modifiers in android studio java class

hello everyone
i am new in android development and i have a code that use simple

intent
to take photo .

public class MainActivity extends AppCompatActivity {

ImageView mImageView =(ImageView)findViewById(R.id.image_view_taken_picture);
static final int request=1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void takePicture(View view )
{
Intent i_picture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(i_picture.resolveActivity(getPackageManager())!=null)
{
startActivityForResult(i_picture,request);
}

}

protected void onActivityResult(int requestCode, int resultCode, Intent dat) {

if(requestCode==request && resultCode==RESULT_OK)
{
Bundle extra = dat.getExtras();
Bitmap image = (Bitmap)extra.get("data");
mImageView.setImageBitmap(image);

}
}


}

but i always get Unfortunately,App has stopped
i know the problem is with the java class more specifically the first two Variables ImageView and int

any help !
and thanks in advance ...

Answer

Your ImageView initialization line is a crash first, you can't initialize your view before setContentView(R.layout.activity_main); because before this line activity don't even know about any XML attached to it so activity will say "hey i don't have anything like R.id.image_view_taken_picture 'cuz i don't have any XML layout"

ImageView mImageView =(ImageView)findViewById(R.id.image_view_taken_picture); // crash

do the initialization in onCreate after setContentView

ImageView mImageView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mImageView =(ImageView)findViewById(R.id.image_view_taken_picture);
    }

Second you don't have to pass the view to takePicture function

public void takePicture()
{
    Intent i_picture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if(i_picture.resolveActivity(getPackageManager())!=null)
    {
        startActivityForResult(i_picture,request);
    }

}

now just call it like this takePicture() whenever you want to take a pic