Android 安卓:使用点击按钮的意图启动活动

Android 安卓:使用点击按钮的意图启动活动,android,onclick,runtimeexception,Android,Onclick,Runtimeexception,我正在尝试使用intent启动活动: public class Bez_provjere_739 extends Activity { Button Tbutun; public void onCreate(Bundle savedInstanceState) { Tbutun.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TO

我正在尝试使用intent启动活动:

    public class Bez_provjere_739 extends Activity { 
Button Tbutun;
 public void onCreate(Bundle savedInstanceState) {

    Tbutun.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent otvoriIn = new Intent("com.riteh.HL.IN");

            startActivity(otvoriIn);
        }
    });
我以同样的方式在我的应用程序中多次使用它,但只有在这种情况下,我才会得到错误:


05-17 00:44:43.694:E/AndroidRuntime(3533):java.lang.RuntimeException:无法启动活动组件信息{com.riteh.HL/com.riteh.HL.Bez_provjere_739}:java.lang.NullPointerException

您从未初始化过按钮,也未分配给它,因此它是空的

此外,您的代码中还缺少一些基本信息:

// naming conventions - variable names start with lower case letter
private Button tbutun; 

@Override
public void onCreate(Bundle savedInstanceState) {
    // always call super.onCreate
    super.onCreate(savedInstanceState);
    // if you have a layout XML, use it
    setContentView(R.layout.lay_xml_name);
    // if the button declared in the layout, refer to it
    tbutun = (Button)findViewById(R.id.the_button_name);
    // the rest
}

初始化你的按钮,试试这个

  public class Bez_provjere_739 extends Activity { 
    Button Tbutun;
     public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);

    Tbutun=(Button)findViewById(R.id.button1) //change the id as per yours

        Tbutun.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent otvoriIn = new Intent("com.riteh.HL.IN");

                startActivity(otvoriIn);
            }
        });

没有setContentView的findViewById肯定会给出null。