0

I'm making a simple app and want a user to click start to move to the next activity but when implementing the start button I keep getting a NullPointerException when it is pressed at runtime. I'm confused because it seems like the FindViewByID is returning null on the ID of the button (startbutton) even though it is included in the XML file. Been stuck on this for hours and have searched for other solutions and tried cleaning and rebuilding. Using Android Studio 2.2.3 if that helps. Thanks.

XML file activity_start_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|center"
android:weightSum="1">

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:text="Quiz App"
    android:textSize="36dp"
    android:gravity="center"
    android:layout_weight="0.34" />

<Button
    android:text="Start!"
    android:layout_width="245dp"
    android:layout_height="50dp"
    android:id="@+id/startbutton" />

</LinearLayout>

Main Activity Code StartScreen.java

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

public class StartScreen extends AppCompatActivity
{
    private Button startbutton;



@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_screen);
    //set start button
    startbutton = (Button) findViewById(R.id.startbutton);
    startbutton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            //go to quiz screen
            //change activity
            Intent QuizScreen = new Intent(StartScreen.this, QuizScreen.class);
            startActivity(QuizScreen);

        }
    });
}
}

Stack Trace

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.paavan.quizappcoursework, PID: 2305
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paavan.quizappcoursework/com.paavan.quizappcoursework.QuizScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               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.paavan.quizappcoursework.QuizScreen.onCreate(QuizScreen.java:63)
                  at android.app.Activity.performCreate(Activity.java:6662)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Application terminated.

QuizScreen.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class QuizScreen extends AppCompatActivity
{
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;

private Question[] mQuestionBank = new Question[] {
        new Question(R.string.question_oceans, true),
        new Question(R.string.question_mideast, false),
        new Question(R.string.question_africa, false),
        new Question(R.string.question_americas, true),
        new Question(R.string.question_asia, true),
        new Question(R.string.question_uk,false),
        new Question(R.string.question_europe,true),
        new Question(R.string.question_waterfall,false),
        new Question(R.string.question_giraffes,false),
        new Question(R.string.question_penguins,true),
};

private int mCurrentIndex = 0;

private void updateQuestion()
{
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue)
{
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_toast;
    } else {
        messageResId = R.string.incorrect_toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}



@Override
protected void onCreate(Bundle savedInstanceState)
{
    mQuestionTextView = (TextView) this.findViewById(R.id.question_text_view);


    mTrueButton = (Button) this.findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            checkAnswer(true);
        }
    });
    mFalseButton = (Button) this.findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            checkAnswer(false);
        }
    });

    mNextButton = (Button) this.findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });

    updateQuestion();

}



}

quizscreen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >



<TextView
    android:id="@+id/question_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="24dp"
    />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/true_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/true_button" />

    <Button
        android:id="@+id/false_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/false_button" />

</LinearLayout>


<Button
    android:id="@+id/next_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/next_button" />

</LinearLayout>

3 Answers3

1

Try this:

LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.activity_start_screen, null);

Button startbutton = (Button) view.findViewById(R.id.startbutton);
Amey Shirke
  • 574
  • 1
  • 5
  • 16
1

You need to add the layout to activity.

Before doing any initialization of widgets in onCreate() add the layout using setContentView(R.layout.your_layoutfile);

public class QuizScreen extends AppCompatActivity
   {
        @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.quizscreenlayout);

    //initialize your widgets
}
Sanjeet
  • 2,275
  • 1
  • 10
  • 21
-1
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener) 
   on a null object reference at 
   com.paavan.quizappcoursework.QuizScreen.onCreate(QuizScreen.java:65)

This null pointer exception is in 65th line in Quizscreen.java. Please check whether all button id's are there in quizscreen.xml.

Daniel Nugent
  • 40,780
  • 13
  • 103
  • 126
Sangeet Suresh
  • 2,309
  • 15
  • 19