0

在我的场景中,我从图库中选择一张图片并将其显示在同一布局的 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);


}

每当我没有选择图像并按下灰度按钮时,它都会强制停止。是否需要放置try-catch?

4

1 回答 1

0
 //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);          
       }
 });  
于 2012-05-22T09:04:02.487 回答