简体   繁体   中英

Android: starting activity using intent on button click

I'm trying to start activitiy using 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);
        }
    });

I use it several times in my aplication in the same way but only in this case i get error:

05-17 00:44:43.694: E/AndroidRuntime(3533): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.riteh.HL/com.riteh.HL.Bez_provjere_739}: java.lang.NullPointerException

You never initialized your button nor assigned to it, so it is null.

Also, there are some basics missing from your code:

// 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
}

Initialize your Button, try this

  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);
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM