Take the 2-minute tour ×

I have a RelativeLayout completely created within java, not using xml layout. I have a few buttons on the left if my screen. I want to click on one button and show a default image from my res/drawable next to the button and make it disappear again on second click. What I have tried was toggling the visibility but my onClick() raises a FATAL EXCEPTION, NullPointer Exception.

This is my code so far. Hardcoded the image shows right when I set picview.setVisibility(View.INVISIBLE); by hand. What I am doing wrong in the onClick() ?

    private ImageView picview;

        //*snip* loads of other code

    //Show Image Button
    ImageButton show_pic = new ImageButton(this);
    show_pic.setOnClickListener(new OnClickListener()

        public void onClick(View v) {
            if(picview.getVisibility() == View.INVISIBLE)
            else if (picview.getVisibility() == View.VISIBLE)


    params = new RelativeLayout.LayoutParams(40, 40);
    params.topMargin = 10;
    params.leftMargin = 10;
    params.addRule(RelativeLayout.BELOW, button2_id);
    rl.addView(show_pic, params);

    //Imageview loaded from drawable
    ImageView picview = new ImageView(this);
    params = new RelativeLayout.LayoutParams(200, 400);
    params.topMargin = 0;
    params.leftMargin = 30;
    params.addRule(RelativeLayout.RIGHT_OF, button2_id);
    rl.addView(picview, params);

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You are accidentally creating two copies of picview. Shorten this line:

ImageView picview = new ImageView(this);


picview = new ImageView(this);

(Your field variable private ImageView picview; never changed from null, so when you clicked your Button you see the NullPointerException...)

share|improve this answer
thank you so much for that quick and understandable reply! –  birgit Nov 11 '12 at 23:41

Your Answer


