如何为不存在图像选择抛出异常

在我的场景中,我从相册中选择一张照片并将其显示在我的imageView中,并且我可以使用该图像处理另一个活动。但是当我点击意图按钮时没有选择任何图像时,我有一个强制停止。

谁有解决这个问题的想法?

public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView (R.layout.browse_page);

    //action for browse Image

        Intent intent = new Intent();       
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);


    //declare image and button
    image = (ImageView) findViewById (R.id.image);
    chooseNewImage = (Button) findViewById (R.id.chooseNewImage);
    grayScale = (Button) findViewById (R.id.greyscale);

    //back to previous page
    chooseNewImage.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
           //TODO Auto-generated method stub
            finish();
        }
    });

    //go to set the image to grayScale
    grayScale.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

                Intent greyScale = new Intent(browsePage.this, grayScale.class);
                greyScale.putExtra("imagePath", path_selectedImage);
                startActivity(greyScale);

        }
    }); 
}

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == SELECT_PICTURE) {


                    Uri_selectedImage = data.getData();
                    path_selectedImage = getPath(Uri_selectedImage);                   
                    image.setImageURI(Uri_selectedImage);
                    System.out.println(path_selectedImage);
                    Toast.makeText(getBaseContext(), "Your selected picture", Toast.LENGTH_SHORT).show(); 
             }


    }

    private String getPath(Uri uri) {
       //TODO Auto-generated method stub
        String[] project = {MediaStore.Images.Media.DATA};
        Cursor c = managedQuery(uri, project, null, null, null);
        startManagingCursor(c);
        int column_index = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        c.moveToFirst();
        return c.getString(column_index);


}

每当我没有选择一个图像,我按下灰度按钮,它强制停止。是否需要尝试抓住?

0
额外 编辑
意见: 1
我想弹出一杯吐司〜
额外 作者 user1381427,
单击灰度并且未选择图像时,您希望发生什么?或者您应该只在选择图像时启用灰度按钮?请同时发布崩溃的logcat。
额外 作者 Simon,

1 答案

 //go to set the image to grayScale     
 grayScale.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {

          if (path_selectedImage==null){
            //show toast here
          } else {     
             Intent greyScale = new Intent(browsePage.this,grayScale.class);
             greyScale.putExtra("imagePath",path_selectedImage);
             startActivity(greyScale);          
       }
 });  
0
额外