App Crashes with java.lang.NullPointerException


#1

There are two closely related posts on this topic with no solution that works for me.
The app crashes as soon as I load it on my device. The line which causes this are the following:

Line 33: mQuestionTextView.setText(question); Line 78: updateQuestion();
Here is my code.
Can anyone please help? Thanks.

[code]package com.bignerdranch.android.geoquiz;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends ActionBarActivity {

private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank = new TrueFalse[] {
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
};

private int mCurrentIndex = 0;


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

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

    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) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

    mQuestionTextView = (TextView)findViewById(R.id.question_text_view);

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

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

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


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.quiz, menu);
    return true;
}

/* @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
[/code]

[code]

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

[/code]


#2

Would it be possible to provide the logcat of the exception generated for this? It’s always the first place to begin when diagnosing exceptions.


#3

09-26 22:21:04.387 3873-3873/com.bignerdranch.android.geoquiz W/Resources﹕ Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f07003c}
09-26 22:21:04.397 3873-3873/com.bignerdranch.android.geoquiz D/AndroidRuntime﹕ Shutting down VM
09-26 22:21:04.397 3873-3873/com.bignerdranch.android.geoquiz W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41be9ba8)
09-26 22:21:04.397 3873-3873/com.bignerdranch.android.geoquiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bignerdranch.android.geoquiz, PID: 3873
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.geoquiz/com.bignerdranch.android.geoquiz.QuizActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.bignerdranch.android.geoquiz.QuizActivity.updateQuestion(QuizActivity.java:33)
at com.bignerdranch.android.geoquiz.QuizActivity.onCreate(QuizActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)


#4

Yep, logcat confirms what you said about where the app is crashing – just wanted to confirm. Curious about your activity_quiz.xml layout file. Is that the complete listing? Looks to be chopped off, but assuming your R class file would not have been generated if it was like that. Could you also post your complete strings.xml file. Want to see the string resources for the questions.


#5

@rcubed: Thanks for your reply. Here is my strings.xml

[code]<?xml version="1.0" encoding="utf-8"?>

<string name="app_name">GeoQuiz</string>
<string name="true_button">True</string>
<string name="false_button">False</string>
<string name="correct_toast">Correct!</string>
<string name="incorrect_toast">Incorrect!</string>
<string name="action_settings">Settings</string>
<string name="next_button">Next</string>

<string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question_africa">The source of the Nile River is in Egypt.</string>
<string name="question_americas">The Amazon River is the longest river in the Americas.</string>
<string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string>

[/code]
Here is complete activity_quiz.xml:

[code]

<TextView
    android:text="@+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"/>
[/code]

#6

Everything with your code looks fine to me. Could you please post your TrueFalse.java file? The only other possibility that I can think of at this point is perhaps your getQuestion() method is returning an invalid string resource ID, but it’s such a simple class it’s unlikely. The only other thing I can think of is to send me a .zip file of your entire project and I can run it here and see what happens.


#7

[code]package com.bignerdranch.android.geoquiz;

public class TrueFalse {

private int mQuestion;

private boolean mTrueQuestion;

public TrueFalse(int question, boolean trueQuestion){
    mQuestion = question;
    mTrueQuestion = trueQuestion;
}

public int getQuestion() {
    return mQuestion;
}

public boolean isTrueQuestion() {
    return mTrueQuestion;
}

public void setQuestion(int question) {
    mQuestion = question;
}

public void setTrueQuestion(boolean trueQuestion) {
    mTrueQuestion = trueQuestion;
}

}[/code]


#8

@rcubed: How do I send the zip file?


#9

You can zip (compress) the entire GeoQuiz project under your Eclipse workspace folder using WinZip if you have it, otherwise, you can download win-rar here for free:

win-rar.com/download.html?&L=0

Once you have that post back and I’ll provide an email address.


#10

I’m using Android Studio 0.8.9. I have the zip file ready. Let me know the email id. Thanks a lot.


#11

I’m using Eclipse, but I can import it. Please send the zip file here:


#12

@rcubed, I have just sent you a link of g-drive location from where you can download the zip file. Let me know if you have any problem. Thanks a lot.


#13

OK, this was a particularly nasty problem to track down. Setting breakpoints both in onCreate and updateQuestion revealed that the reference for mQuestionTextView was coming back as null. This was a case where the compiler was perfectly fine with your code, but the runtime sure wasn’t. It wasn’t until I compared my quiz_activity.xml layout file side-by-side with yours that I found the problem:

Study that line for a bit and see if you can find what’s wrong. The majority of the problems reported here are the result of simple typos. This could be a case where code completion might have steered you wrong. Hint: you’re attempting to assign the view id here for the TextView and the xml attribute name doesn’t match up with what you’re hoping to accomplish.


#14

Yes, code completion sometimes can be really nasty. I actually checked this section number of times; But, I always checked if the name is correct rather than the property. :astonished:
Thanks very much @rcubed for your help and debugging my code.

And as expected with the above change now it works. :geek:


#15

What’s interesting about this situation is the resource compiler assigns IDs to all resources regardless if you declare an id element for it in an xml layout file. First thing I checked was the generated id in the R.class file and it was present for this TextView widget. You only need to declare an id element if you wish to reference the control externally from within code.


#16

rcubed: you rock. I’m so happy to have found your solution after suffering with this problem for hours and hours.
wow. such joy


#17

Glad it helped you out. I think we’ve all banged our heads against the proverbial wall over problems that make no sense to us only later to find out it was something very simple. It was anything but simple while struggling to find the problem, though. Sometimes all that’s required is another pair of eyes on the problem. That’s why it’s good not to be afraid of asking a colleague at work or online to have a look – it can save a lot of time and frustration.