I’ve got 2 layout files in res/layout folder: main.xml and page2.xml.
In the main.xml I’ve got welcome info and button which starts
setContentView(R.layout.page2);
to change to page2.xml.
It worked fine till I decided to add Gallery view in page2.xml.
When I set from begining ContentView to page2 like below it’s ok.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
But when I call main.xml first to show may start page…
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
the app returns error.
I know that the problem is with Context in line
g.setAdapter(new ImageAdapter(this));
but I completely don’t know how to pass right context or solve it in another way (but I don’t want to have all layout in one xml file).
It’s not entirely clear from your explanation (logs never hurt), but I think you’re getting a null pointer exception because
galleryis not defined in yourmain.xml. There are two solutions for your problem:startActivity()and then callfinish(), so your welcome activity is not left hanging about.findViewById()acts on whatever is “visible” in the activity right now. Since you didsetContentView(main), yourGallerywill not be there. Try “getting” the gallery only after you make the call to “change pages” (setContentView(R.layout.page2);).However, I would strongly advice you go with the first option.