I have an Activity which has two different layouts based on grid view and full page gallery view, when user clicks on an image in grid view it goes to full screen gallery. When the user in full screen Gallery and when back button is clicked it goes back to grid view. Finally if the user again clicks back button once more I want Activity to terminates.
Here is How I handle switching views on back button pressed, It works well except finishing activity. I have null pointer exception on the line I call finish(). How can I handle it?
@Override
public void onBackPressed() {
ViewPager mPager = (ViewPager) findViewById(R.id.gallery_view);
if(mPager.getVisibility() == View.VISIBLE){
setContentView(R.layout.thumbnail_gallery);
GridView g = (GridView) findViewById(R.id.myGrid);
g.setAdapter(new GridGallery(this));
return;
}else {
finish();
return;
}
}
I have found the reason of
NullPointerExceptionin the end. The methodfindViewByIdcauses it. Instead of checking the visibility of the layout, I have used a boolean variable to check it. Basically when I set the the content view to a layout I assign this variable to true, and then when I switch the view I also switch the boolean variable to false. It works quite well.And in the place I switch the view I assign it to true. Take a look below.