1

In my Android application, I have two activity classes. I have a button on the first one and I want to show the second when it is clicked, but I get an error. Here are the classes:

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startButton = (Button)findViewById(R.id.startBtn);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, StartField.class);
                startActivity(intent);
            }
        });
    }
}

Here is the second class:

public class StartField extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_layout);

        Button startButton = (Button) findViewById(R.id.end);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}

I added second class in Manifest file. When I press that button, error comes up and in logcat it says

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.tavatievs.kurstoti.StartField.onCreate(StartField.java:20)
Ninjakannon
  • 3,283
  • 5
  • 42
  • 65
  • `startButton` is null. You're using the wrong ID or it's not defined correctly. Google "What is a null pointer exception and how do I fix it". – Kon Apr 28 '15 at 23:15
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Kon Apr 28 '15 at 23:15
  • This isn't *usefully* a duplicate of the *generic* NPE question. Here we have all the information necessary to know exactly what is null. The only question is why - was the wrong layout set as the content view, or was the button identifier mis-stated? – Chris Stratton Apr 29 '15 at 01:35

0 Answers0