I have an app that is setting the contentView when images are clicked.This one from my main.xml loads the options.xml fine.
settings.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
setContentView(R.layout.options);
}
});
But when I add a listener to an image that is inside the options.xml the app crashes upon launch.I am referencing the image via the code below and showing the clickListener I am adding.
//ReturnHome is inside options.xml
//Adding this in my mainapp.java
returnHome = (ImageView)findViewById(R.id.returnHome);
returnHome.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
***APP CRASHES EVERY TIME WHEN I ADD THIS****
}
});
Trying to see if there was an error thrown but LogCat does not seem to show anything.
findViewByIdfor the returnHome image is in context of the application.If in your applicaiton
onCreate()you setsetContentView(R.layout.main);when you callfindViewByIdit will be looking atmain.xmlfor the imagereturnHome, which obviously isn’t there because its onoptions.xml, as a result you will get a NullPointerException, because if can’t find what you are asking it to.Instead of declaring the image listener for returnHome in the context of main.xml try doing it after changing the layout, maybe as a method:
Then change the first onclick listener to: