Setonclicklistener Is Causing "runtimeexception: Unable To Start" - Nullpointerexception
I got an error, and I can't understand what's causing it. This is the snippet of code that generates the error: public class RssReader extends Activity { private Button button1; @O
Solution 1:
You have to call setContentView(R.layout.rss_reader);
before registering your OnClickListeners
.
package com.cris96.rssreader;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
publicclassRssReaderextendsActivity {
private Button button1;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss_reader);
button1 = (Button) findViewById(R.id.b1);
button1.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
System.out.println("test");
}
});
}
}
Solution 2:
You need to do it this way:
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss_reader);
button1 = (Button)findViewById(R.id.b1);
button1.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
System.out.println("test");
}
});
}
You can't set the find the view before set the layout as a content of the Activity.
This is the reason that findViewById
returns null.
Post a Comment for "Setonclicklistener Is Causing "runtimeexception: Unable To Start" - Nullpointerexception"