Phobos
Phobos

Reputation: 9557

Missing Something Easy (Button OnClick Causing Null Pointer)

Suddenly my buttons cause null pointer exceptions. I have not changed any code in this activity class. I have been up most of the weekend trying to pin this down. I get null pointer exceptions in both the emulator and on device.

This is a simple screen with buttons. I could easily scrap this and write new code, but would like to know what has caused this issue. If not, I will just write new code.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


Button b1 = (Button) findViewById(R.id.MainActBtn);

b1.setOnClickListener(new View.OnClickListener() { //Error is here

        public void onClick(View v) {
            Intent intent = new Intent(StartScreen.this, MainActivity.class);
            startActivity(intent);

        }
    });

Any help?

Upvotes: 0

Views: 814

Answers (2)

HefferWolf
HefferWolf

Reputation: 3924

Try a fresh clean and build of your project. I got this error too in the past, caused by a changed R.class Resource class, but the static references in the using classes weren't properly replaced by the incremental java compiler, so the resources are no longer found.

Upvotes: 2

MKJParekh
MKJParekh

Reputation: 34301

I think You are not getting Null Pointer Exception because of the Button click just because of the declaration of the button..

You can check before writting the onClickListener..

if(b1==null)
 Log.i("Null","Null");

The Problem is may be in setting the XML view or also check the button you are using is defined in the same xml you are using in setContentView.

After this all, also Clean and Build your project.

Upvotes: 1

Related Questions