Reputation: 808
I've been trying Android Studio and I've struggled at the beginning. I want to create a button that pops a Toast message on a click. I wrote a simple code, but the program starts and then Android shuts it down. I don't really understand, because this code works perfectly in Eclipse, it's really easy. Is it just an Android Studio problem or am I so bad? Imports are ok. When I run a plain new project, it runs. It crashes only with the new onClick button.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button button;
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
writeIt();
}
});
}
Upvotes: 1
Views: 4727
Reputation: 495
Did you add a Button view to the activity_main.xml file? By default it seems that Android Studio populates it with a fragment only. If that's the case, your call to setOnClickListener will throw a NullPointerException.
Upvotes: 1