I have a view that I’m loading, and my onCreate() method looks like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
volume_id=getIntent().getStringExtra("volume_id");
language=getIntent().getStringExtra("language");
chapter=Integer.parseInt(getIntent().getStringExtra("chapter"));
book=getIntent().getStringExtra("book");
book_id=getIntent().getStringExtra("book_id");
final Button back=(Button)findViewById(R.id.backButton);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(Verse.this, "Back", Toast.LENGTH_LONG).show();
}});
final Button next=(Button)findViewById(R.id.forwardButton);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(Verse.this, "Next", Toast.LENGTH_LONG).show();
}});
}
For some reason, the addition of those last several lines of code, that link up to two buttons I’ve made in the layout file, are making my app crash. I am not getting anything in the error log, so I have absolutely no idea what is going on.
It may be good to note that without that button adding code in my view, the view loads fine, and the buttons show up where they are supposed to.
Does the way I’m adding those buttons look alright? Am I doing something wrong? I wish it wasn’t so hard to hook up a GUI button to code…
Thanks
To answer your question:
You need to call
setContentView(R.layout.main)(or whatever your layout file is called) before you can callfindViewById. Also, thefinalkeyword might be messing your code up, but that’s probably not the issue.Other possibly helpful information: (You don’t technically need to read any of this)
Your code’s formatting is also very messy. Consider this:
Notice:
1. Spaces before and after each
=2. Spaces after type casting parentheses (e.g. “
(Button)“)3. Correct indentation
4. No extraneous blank lines (for example, between @Override and public void onClick
5. Helpful comments
It’s the little things that make your code easier to read from other programmers.
Also, you might want to consider passing “chapter” as an intExtra instead of parsing it from a String. That wastes precious memory. Change the instance field String to int. Finally, you might want to consider making the Buttons instance fields for the entire class as well.