Java android, getting image from gallery and show it on screen (error)

时光怂恿深爱的人放手 提交于 2019-12-14 03:55:23

问题


First time I post a question, so here it goes.
I want to push on a button, so it opens the gallery, pick a picture, then shows it somewhere on the screen (layout).

I got this far by now:

public void FotoKiezen(View v) {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, 1);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 1:
     {
      if (resultCode == RESULT_OK)
      {
        Uri photoUri = data.getData();
        if (photoUri != null)
        {
        try {
              String[] filePathColumn = {MediaStore.Images.Media.DATA};
              Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
         cursor.moveToFirst();
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
     String filePath = cursor.getString(columnIndex);
     cursor.close();
     Bitmap bMap = BitmapFactory.decodeFile(filePath);
     ImageView.setImageBitmap(bMap);


     }catch(Exception e)
      {}
      }
    }// resultCode
    }// case 1
    }// switch, request code
}// public void onActivityResult

There is some other code above it too, but here somewhere is the problem.

I get an error on the line ImageView.setImageBitmap(bMap); The error:

Cannot make a static reference to the non-static method setImageBitmap(Bitmap) from the type ImageView

I searched a lot on the internet, and tried many things, but I can't resolve it. Maybe it is really easy and I just don't see it.

I am beginner at Java android programming, used to program in C++. So also some explanation about the error would be very nice :D


回答1:


You must create the object of ImageView class? For example:

ImageView img = new ImageView(this);
img.setImageBitmap(bMap);

or

ImageView img = (ImageView)findViewById(R.id.<your image view id>);
img.setImageBitmap(bMap);



回答2:


I think this line cause error..

ImageView.setImageBitmap(bMap);

Here ImageView is a class, instead of this you have to create a object of it then use setImageBitmap to it.,

ImageVIew mImageView = new ImageView(this)
mImageView.setImageBitmap(bMap);

Or if you have already defined ImageView object in your activity then just use that..



来源:https://stackoverflow.com/questions/9094459/java-android-getting-image-from-gallery-and-show-it-on-screen-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!