0

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?

4
  • have you add MainActivity activity in manifest file? Commented Oct 17, 2011 at 9:20
  • Add your layout xml or make sure you put the right id and done this process after setContentView() Commented Oct 17, 2011 at 9:21
  • Yes. The error is actually pointing to the onclicklistener line Commented Oct 17, 2011 at 9:22
  • whaat does error say when point on it??? Commented Oct 17, 2011 at 9:27

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it would be something extremely easy. After a complete clean and rebuild the R resources were recompiled. Eclipse sometimes does things that I am not aware of.
1

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.

2 Comments

I have all ready added the line in order to check before I posted the question.
Frank, I had to uncheck Build Automatically, and the clean the project, and then recheck Build Automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.