NullPointerException at Home.onCreate
I am trying to run a test program that allows a user to click a button and move to a different screen. I have the Home(First Activity) and Away(Second Activity) classes and a xml file specifying the layout for each. My source code is as follows:
public class Home extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button create = (Button)findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Home.this, Away.class);
startActivity(intent);
}
});
setContentView(R.layout.main);
}
}
And Away.java
public class Away extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.away);
}
}
I get a NullPointerException in the DDMS trace
at Home.onCreate(line 17)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at and开发者_如何学Goroid.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2627)
Anyone see anything in my code that may be causing this?
findViewById()
traverses the view hierarchy set up when setContentView()
inflates your layout. You cannot retrieve a reference to a view in your XML before you have called setContentView()
. Change your onCreate()
method in Home to look like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Call me first
setContentView(R.layout.main);
Button create = (Button)findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Home.this, Away.class);
startActivity(intent);
}
});
}
Otherwise, findViewById()
will return null because there are no views in the tree...thus, a view with your requested id value doesn't exist.
Hope that helps!
If the findViewById
call can't find the actual thing you are looking for, it could return a null
object and cause the call to setOnClickListener
to throw an NPE. Are you sure you've got the right ID (R.id.create
) specified?
精彩评论