Skip to content
Advertisement

I cannot set a onclick listener for image button

public class HomeActivity extends AppCompatActivity{
RecyclerView chillHits;
RecyclerView coolSongs;
HomeAdaptor homeAdaptor;
SongCollection songCollection = new SongCollection();

ImageButton imageButton;
ImageButton imageButton2;
ImageButton imageButton3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    imageButton = findViewById(R.id.imageButton2);
    imageButton2 = findViewById(R.id.imageButton3);
    imageButton3 = findViewById(R.id.imageButton4);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getApplicationContext(), SearchActivity.class));
            finish();
        }
    });

    setContentView(R.layout.activity_home);

    LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    LinearLayoutManager horizontalLayoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);


    chillHits = findViewById(R.id.chillHits);
    homeAdaptor = new HomeAdaptor(SongCollection.arrayChillHits);
    chillHits.setAdapter(homeAdaptor);
    chillHits.setLayoutManager(horizontalLayoutManager);

    coolSongs = findViewById(R.id.coolSongs);
    homeAdaptor = new HomeAdaptor(SongCollection.arrayCoolSongs);
    coolSongs.setAdapter(homeAdaptor);
    coolSongs.setLayoutManager(horizontalLayoutManager2);
}



}

Error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference

Advertisement

Answer

1)You forgot about setContentView(R.layout.YOURLAYOUT) after super.onCreate

2)Make sure, that your XML file have the same ImageView ID

Advertisement