简体   繁体   中英

Android app crashes after launching intent and using setText() in TextView

I'm trying to launch an activity using intents and setting values in TextViews in the launched activity, but when I try to do that my app crashes. Heres the activity I'm trying to launch. It crashes when i try to set the text in the last two code lines

public class GameOver extends Activity {

  TextView correctTxt;
  TextView incorrectTxt;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      Intent intent = getIntent();
      int correct = intent.getIntExtra("correct", 0);
      int incorrect = intent.getIntExtra("incorrect", 0);

      correctTxt = (TextView)findViewById(R.id.correct_txt);
      incorrectTxt = (TextView)findViewById(R.id.incorrect_txt);

      correctTxt.setText("" + correct);
      incorrectTxt.setText("" + incorrect);
  }
}

And the activity that's launching. I make use of the intent in the trueButton onClickListener method:

package com.example.beithia.geotest;

import android.app.Activity;
import java.util.*;

import android.content.Intent;
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;
import android.content.Intent;


public class TestActivity extends Activity {

  private Button trueButton;
  private Button falseButton;
  private TextView questionTextView;
  private TextView correctNum;
  private TextView incorrectNum;
  private TextView avgScore;
  int numOfCorrect = 0;
  int numOfIncorrect = 0;
  double num = 1;

  private TrueFalse[] questionBank = new TrueFalse[] {
    new TrueFalse(R.string.question_oceans, true),
    new TrueFalse(R.string.question_mideast, false),
    new TrueFalse(R.string.question_americas, true),
    new TrueFalse(R.string.question_asia,true),
    new TrueFalse(R.string.question_channel_islands,true),
    new TrueFalse(R.string.question_china,false),
    new TrueFalse(R.string.question_mexico,true),
    new TrueFalse(R.string.question_turkey,false),
    new TrueFalse(R.string.question_everest,false),
    new TrueFalse(R.string.question_colombia,false),
    new TrueFalse(R.string.question_vatican,true),
    new TrueFalse(R.string.question_nile,true),
  };

  private int currentIndex = 0;

  private void updateQuestion() {
    int question = questionBank[currentIndex].getQuestion();
    questionTextView.setText(question);
  }

  private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = questionBank[currentIndex].isTrueQuestion();
    int msgId = 0;
    if (userPressedTrue == answerIsTrue) {
        msgId = R.string.correct_toast;
        numOfCorrect++;
    }
    else {
        msgId = R.string.incorrect_toast;
        numOfIncorrect++;
    }
    Toast.makeText(this,msgId,Toast.LENGTH_SHORT).show();
  }


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    questionTextView = (TextView)findViewById(R.id.question_text_view);
    correctNum = (TextView)findViewById(R.id.correct_num);
    incorrectNum = (TextView)findViewById(R.id.incorrect_num);
    avgScore = (TextView)findViewById(R.id.average_score);


    trueButton = (Button) findViewById(R.id.true_button);
    trueButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          checkAnswer(true);
          double score = (numOfCorrect / num) * 100;
          currentIndex = (currentIndex + 1) % questionBank.length;
          correctNum.setText("Correct: " + numOfCorrect);
          incorrectNum.setText("Incorrect: " + numOfIncorrect);
          avgScore.setText("Score: " + String.format("%.2f", score) + "%");
          updateQuestion();
          num++;
          if(num > 10) {
            Intent intent = new Intent(TestActivity.this, GameOver.class);
            intent.putExtra("correct", numOfCorrect);
            intent.putExtra("incorrect", numOfIncorrect);
            startActivity(intent);
          }

      }

    });
    falseButton = (Button) findViewById(R.id.false_button);
    falseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          checkAnswer(false);
          double score = (numOfCorrect / num) * 100;
          currentIndex = (currentIndex + 1) % questionBank.length;
          correctNum.setText("Correct: " + numOfCorrect);
          incorrectNum.setText("Incorrect: " + numOfIncorrect);
          avgScore.setText("Score: " + String.format("%.2f", score) + "%");
          updateQuestion();
          num++;

        }

    });

    updateQuestion();
  }
}

Here's the layout for activity_main.xml:

    <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/correct_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff00ff12" />

    <TextView
        android:id="@+id/incorrect_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffff5440" />

    <TextView
        android:id="@+id/average_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffff8c1a" />

    <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>
</LinearLayout>

And the layout for the activity_game_over.xml:

    <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/correct_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

   <TextView
       android:id="@+id/incorrect_txt"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

    </LinearLayout>

I can get it to work if I use the setContentView(R.layout.activity_game_over); however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead.

GameOver活动中,您未设置任何内容视图setContentView() ,因此无法找到findViewByIdfindViewById返回null ,因此在调用setText()时会收到NullPointerException。

I can get it to work if I use the setContentView(R.layout.activity_game_over); however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead. Please help!

The activity that runs at start up is defined in the android manifest xml file of your project.

look for action android:name="android.intent.action.MAIN"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM