47
votes

This is my xml, this is located inside a fragment that appears in my activity.

<FrameLayout
                    android:id="@+id/frame1"
                    android:layout_width="wrap_content"
                    android:layout_height="115dp"
                    android:layout_margin="2dp"
                    android:layout_weight="0.33">

                    <ImageView
                        android:id="@+id/whoamiwith"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:scaleType="fitCenter"
                        android:src="@drawable/default_image" />
                </FrameLayout>

And this is my java code :

@Override
public void onClick(View click) {
    if (click == profileBtn) {
        whoamiwith.setBackgroundResource(R.drawable.image_i_wanna_put);
    }
}

I am trying to change the image source of the image view. There are no syntax errors but when I click the button the emulator is giving me a force close and on the logcat it says:

java.lang.NullPointerException

It's pointing to the line:

whoamiwith.setBackgroundResource(R.drawable.loginbtn);
6
You need to check like click.getId() == profileBtn. And share your code how you initialize your whoamiwith ? - Hardik Joshi
have you initialized your whoamiwith ? - A.S.
There is a problem with your initialization. Check your imageview id. - Rethinavel
ImageView whereami = (ImageView) findViewById(R.id.whereami); i got it this way guys.. - CENT1PEDE
How you dealt with "whoamiwith" You have only initialized whoamiwith rite? How about whereami? and you are trying to set background image with initializing that! - Rethinavel

6 Answers

105
votes
whoamiwith.setImageResource(R.drawable.loginbtn);
12
votes
 ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
 Drawable new_image= getResources().getDrawable(R.drawable.loginbtn);   
    whoamiwith.setBackgroundDrawable(new_image);
5
votes

Just try

ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
whoamiwith.setImageResource(R.id.new_image);
3
votes

Initialize image view :

whoamiwith = findViewByid(R.id.whoamiwith);

Then on Click method, write this lines to change the image resource :

 if(android.os.Build.VERSION.SDK_INT > 15)
    {
        // for API above 15
        whoamiwith.setBackground(getResources().getDrawable(R.drawable.loginbtn));
    }
    else
    {
        // for API below 15
        whoamiwith.setBackgroundDrawable(getResources().getDrawable(R.drawable.loginbtn));
    }
3
votes
ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith);
whoamiwith.setImageResource(R.drawable.image_i_wanna_put);
2
votes

Exception is whoamiwith is null. did u initialise whoamiwith like, ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)

Refer Using setImageDrawable dynamically to set image in an ImageView