Nima Sa
Nima Sa

Reputation: 89

Can't get Image from drawable by code

I have an Imageview that when user clicks on it a dialog box opens and it is suppose to show image larger within it.
the Imageview I have is in a layout and the code is this: ImageView image_terrain = (ImageView)findViewById(R.id.imageView2); image_terrain.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent intent = new Intent(getApplicationContext(), Universitymap.class);
            intent.putExtra("imageName", "sattelite");

            Dialog d = new Dialog(Universitymap.this);
            d.setContentView(R.layout.image_dialog);
            d.show();
        }
    });

I use intent for sending which picture clicked by sending it's name.

now in image_dialog layout I have this code:

Intent intent = new Intent();
String fileName = intent.getExtras().getString("imageName");
loadImage(fileName);

and the function that loads image in image_dialog layout class is:

private void loadImage(String fileName){
    ImageView img = (ImageView)findViewById(R.id.img_Picture);
    int resID = getResources().getIdentifier(fileName, "drawable", "com.neema.smobile.Main");
    img.setImageResource(resID);
}

one word = it doesn't work. I would be happy if anyone help.

Upvotes: 2

Views: 543

Answers (2)

Murmel
Murmel

Reputation: 5702

Why are you passing the filename via an Intent? If you are creating the Dialog in the same activity you could create a custom Dialog with a custom Constructor and overgive the filename.

Also i think this line doesn't make sense:

Intent intent = new Intent();
String fileName = intent.getExtras().getString("imageName");

Since you are trying to catch the String from a new Intent, instead of the Intent you sent.

Or did I missunderstood youre way?

The Intent is for starting Activities not for Dialogs :)

Edit:

class CustomDialog extends Dialog{
    private String fileName;
    public CustomDialog(String fileName){
        this.fileName = fileName;
        this.setContentView(R.layout.your_dialog_layout);

    }

   @Override
   public void onCreate(Bundle savedInstanceState){
       ImageView image = (ImageView) findById(R.id.image);
       image.setBackgroundResource(....//set your Image like mentioned from kumaand using your saved fileName
   } 
}

Should work. For more Information you could look at http://about-android.blogspot.de/2010/02/create-custom-dialog.html

Upvotes: 0

kumar_android
kumar_android

Reputation: 2263

Try this

int imageResource = getResources().getIdentifier(fileName, null, getPackageName());

imageview = (ImageView)findViewById(R.id.img_Picture);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);

Upvotes: 1

Related Questions