Search code examples
androidnullreferenceexception

Null pointer exception trying to invoke virtual method on a null object reference android studio


I am trying to hide a button in my android program. I have a button with an id "btn_add" in my XML layout file. Now i want it to be invisible when the activity is opened. I am getting an error "Error trying to invoke a virtual method on a null object reference" on the line where i set the visibility to "View.INVISIBLE" when I check for errors in my logcat.

I also get the same error when i create an onlcick listener to an imageview called "like" with an id "btn_like". The following java code is responsible for that.

Your immediate help would be greatly appreciated.

Button btn_add;
ImageView like;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    btn_add=findViewById(R.id.add_product);
    btn_add.setVisibility(View.INVISIBLE);

    like = findViewById(R.id.like);

    like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(BusinessActivity.this,"liked",Toast.LENGTH_SHORT).show();

        }
    });

}}


Solution

  • This line is missing in your code below super.oncreate(). A contentView is not set. Set the contentview before accessing UI elements.

        setContentView(R.layout.your_activity_xml_layout);
    

    Finally

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.your_activity_xml_layout);
    
    btn_add=findViewById(R.id.add_product);
    btn_add.setVisibility(View.INVISIBLE);
    
    like = findViewById(R.id.like);
    
    like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(BusinessActivity.this,"liked",Toast.LENGTH_SHORT).show();
    
        }
    });
    

    }}