android app force closes
i have this android code .I have my layout for button defined in the xml file .i want to s开发者_开发问答et the text for button here by getting it by id .but the app force closes.whats wrong ?
package com.action ;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class ActionActivity extends Activity {
@Override
public void onCreate(Bundle i){
super.onCreate(i);
Button button=(Button) findViewById(R.id.but);
button.setText("Hey!!");
setContentView(R.layout.main);
}
}
Thnx...
You have to use setContentView(R.layout.main);
before using findViewById()
.
If you don't do that, findViewById()
will return null
(since no view with that ID is in the current layout) and you will get a NullPointerException
when trying to set the text on the TextView
.
The correct version of onCreate()
should look like this:
public void onCreate(Bundle i) {
super.onCreate(i);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.but);
button.setText("Hey!!");
}
Put setContentView(R.layout.main) before creating the instance of Button. Like This:
setContentView(R.layout.main);
Button button=(Button) findViewById(R.id.but);
button.setText("Hey!!");
you must put setContentView(R.Layout.main) before setting findViewById(R.id.but).Because it generates nullpointer Exception.
精彩评论