Reputation: 2490
Why is mainB_news
allways null
? (in the method onBackPressed()
)
In onCreate
I set a value to the button!!! :(
PS: with findViewById()
I get the same error...
public class MainActivity extends Activity {
private Button mainB_news;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainB_news = (Button) findViewById(R.id.mainB_news);
mainB_news.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.news);
}
});
}
@Override
public void onBackPressed() {
// check if page 2 is open
if (mainB_news != null && mainB_news.isShown()){
setContentView(R.layout.main); // open main view again
return;
}else
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
THANKS a lot!
Upvotes: 1
Views: 152
Reputation: 20356
Because you change contentView on button click. mainB_news
doesn't exist after contentView changing. You shouldn't use setContentView()
in this manner. Consider using another activity for showing news.
Upvotes: 1