java - 在共享首选项上打开第二个 Activity/错误时出错

标签 java android sharedpreferences

我正在编写一个包含 1 个问题、3 个选择和 1 个正确答案的测验应用程序。问题、选择和答案都在 QuestionLibrary 类的数组中。 QuizActivity(主要 Activity )中的其他内容现在我设置为当问题完成时,分数将被传输到另一个 java 类(menu2)中的 TextView 但是当所有问题都完成时错误:

尝试在空对象引用上调用虚方法 void android.widget.TextView.setText(java.lang.CharSequence)

显示。哪里出错了,求助

package amapps.impossiblequiz;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private Toolbar mToolbar;
    private MenuItem menuItem;
    private Intent in;

    private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

    private TextView mScoreView;
    private TextView mQuestionView;
    private Button mButtonChoice1;
    private Button mButtonChoice2;
    private Button mButtonChoice3;

    private String mAnswer;
    private int mScore = 0;
    private int mQuestionNumber = 0;

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

        //Randromize the row of the questions
        QuestionLibrary q = new QuestionLibrary();
        System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
                q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
        q.shuffle();
        System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
                q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));

        //End randomizer

        mToolbar = (Toolbar) findViewById(R.id.nav_action);

        setSupportActionBar(mToolbar);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"


        NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem){
                switch (menuItem.getItemId()){
                case(R.id.nav_stats):
                    Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
                startActivity(accountActivity);
                }
                return true;
            }
        });

        mScoreView = (TextView) findViewById(R.id.score_score);
        mQuestionView = (TextView) findViewById(R.id.question);
        mButtonChoice1 = (Button) findViewById(R.id.choice1);
        mButtonChoice2 = (Button) findViewById(R.id.choice2);
        mButtonChoice3 = (Button) findViewById(R.id.choice3);


        updateQuestion();

        //Start of Button Listener1
        mButtonChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice1.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();


                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
                    mScore = 0;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();
                }
            }
        });
        //End of Button Listener1

        //Start of Button Listener2
        mButtonChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice2.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();

                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();
                    mScore = 0;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();
                }
            }
        });
        //End of Button Listener2

        //Start of Button Listener3
        mButtonChoice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice3.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();

                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();
                    mScore = 0;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();
                }
            }
        });
        //End of Button Listener3

    }

    private void updateQuestion() {

        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
            mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
            mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
            mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));

            mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
            mQuestionNumber++;
        }
        else {
            Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(QuizActivity.this, Menu2.class);
            intent.putExtra("score",mScore); //pass score to Menu2
            startActivity(intent);
        }
    }

    private void updateScore ( int point){
        mScoreView.setText("" + mScore);

    }

    @Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
    public boolean onOptionsItemSelected (MenuItem item){
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

public class QuestionLibrary {

    private final String[] [] mChoices ={
            {"1993", "1986", "1967"},
            {"-260", "-272,15", "279,15"},
            {"a plant","The active substance of marijuana" , "a spider"},
            {"6", "10","8"},
            {"12","15","10"},
            {"Uranus","Neptune","Saturn"},
            {"HCl","NaCl","CO"},
            {"John F. Kennedy", "Richard Nixon","James A. Garfield"},
            {"Canada","Denmark", "Greenland is an own state?"},
            {"12","20","14"},
            {"10","12","14"},
            {"not","never","now"},
            {"Leningrad","Wolgograd","Dimitrijgrad"}

    };
    private final String mQuestions[] = {
            "When was the European Union founded?",
            "How many Grad Celsius is one Kelvin?",
            "What is THC?",
            "How many legs has a spider?",
            "How many stars has the European flag?",
            "Which is the seventh planet from the sun?",
            "What is the chemical formula of salt?",
            "Who said: Ich bin ein berliner?",
            "To which country belongs Greenland?",
            "What is the result of: 2 + 2 *5?",
            "How many mountains are higher than 8000 meter/26.246 ft?",
            "A famous quote is: to be, or____ to be!",
            "What is the name of Stalingrad nowadays?"

    };

    private final String mCorrectAnswers[] = {
            "1993", "-272,15", "The active substance of marijuana",
            "8", "12","Uranus","NaCl","John F. Kennedy",
            "Denmark","12","14","not","Wolgograd"

    };

    private final List<Integer> indexes = new ArrayList<>();

    public QuestionLibrary() {
        for (int i = 0; i < mQuestions.length; ++i)
            indexes.add(i);
    }

    private int index(int i) {
        return indexes.get(i);
    }

    public String getQuestion(int a) {
        return mQuestions[index(a)];
    }

    public String getChoice1(int a) {
        return mChoices[index(a)][0];
    }

    public String getChoice2(int a) {
        return mChoices[index(a)][1];
    }

    public String getChoice3(int a) {
        return mChoices[index(a)][2];
    }

    public String getCorrectAnswer(int a) {
        return mCorrectAnswers[index(a)];
    }

    public int getLength() {
        return mQuestions.length;
    }

    public void shuffle() {
        Collections.shuffle(indexes);
    }

}

package amapps.impossiblequiz;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;

import static amapps.impossiblequiz.R.id.nv2;

public class Menu2 extends AppCompatActivity {

    private DrawerLayout mDrawerLayout2;
    private ActionBarDrawerToggle mToggle;
    private Toolbar mToolbar;

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

        TextView txtScore = (TextView) findViewById(R.id.score_score);
        TextView txtHighScore = (TextView) findViewById(R.id.textHighScore);
        Intent intent = getIntent();
        int score = intent.getIntExtra("score",0);
        txtScore.setText("score" +score);

        mToolbar = (Toolbar)findViewById(R.id.nav_action);
        setSupportActionBar(mToolbar);
        mDrawerLayout2 = (DrawerLayout) findViewById(R.id.drawerLayout2);

        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout2, R.string.open, R.string.close);
        mDrawerLayout2.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        NavigationView mNavigationView = (NavigationView) findViewById(nv2);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem){
                switch (menuItem.getItemId()){
                case(R.id.nav_home2):
                    Intent accountActivity2 = new Intent(getApplicationContext(),QuizActivity.class);
                startActivity(accountActivity2);

                }
                return true;
            }
        });
    }

   @Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

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

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="amapps.impossiblequiz.QuizActivity"
    android:orientation="vertical" android:weightSum="1" android:id="@+id/drawerLayout">

    <RelativeLayout android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include layout="@layout/navigation_action"
            android:layout_height="wrap_content" android:layout_width="match_parent" />

        <TextView android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="SCORE" android:id="@+id/score_text"
            android:textSize="20sp" android:textColor="#000"
            android:layout_marginTop="70dp" android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/imageView2" android:layout_toEndOf="@+id/imageView2"
            android:layout_marginLeft="11dp" android:layout_marginStart="11dp" />

        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="0" android:id="@+id/score_score"
            android:textSize="20sp" android:textColor="#000"
            android:layout_marginRight="20dp" android:layout_marginTop="20dp"
            android:layout_alignBaseline="@+id/score_text"
            android:layout_alignBottom="@+id/score_text"
            android:layout_alignParentRight="true" android:layout_alignParentEnd="true" />

        <TextView android:layout_width="match_parent"
            android:layout_height="70dp" android:text="When was the European Union founded?"
            android:textSize="20sp" android:padding="8dp" android:id="@+id/question"
            android:textAlignment="center" android:textColor="#000"
            android:layout_below="@+id/score_text"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" android:layout_marginTop="19dp" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="1993"
            android:background="#f60" android:textColor="#ffffff"
            android:padding="8dp" android:id="@+id/choice1" android:textSize="17dp"
            android:layout_below="@+id/question" android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" android:layout_marginTop="39dp"
            android:layout_marginBottom="8dp" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="1986"
            android:background="#f60" android:textColor="#ffffff"
            android:padding="8dp" android:id="@+id/choice2" android:textSize="17dp"
            android:layout_below="@+id/choice1" android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" android:layout_marginTop="11dp" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="1967"
            android:background="#f60" android:textColor="#ffffff"
            android:padding="8dp" android:id="@+id/choice3" android:textSize="17dp"
            android:layout_marginTop="21dp" android:layout_below="@+id/choice2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <Button android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="quit"
            android:background="#B71c1c" android:textColor="#fff"
            android:padding="8dp" android:id="@+id/quit" android:textSize="17dp"
            android:layout_marginTop="19dp" android:layout_below="@+id/choice3"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <ImageView android:id="@+id/imageView2"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/star_on" android:layout_marginLeft="11dp"
            android:layout_marginStart="11dp" android:layout_alignBottom="@+id/score_text"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content" android:layout_height="match_parent"
        app:menu="@menu/navigation_menu" android:layout_gravity="start"
        android:id="@+id/nv1" app:headerLayout="@layout/navigation_header"
        app:itemIconTint="@drawable/tint_color_selector">

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="amapps.impossiblequiz.Menu2"
    android:id="@+id/drawerLayout2">

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent" android:orientation="vertical">

        <include layout="@layout/navigation_action"
            android:layout_width="match_parent" android:layout_height="wrap_content" />

        <TextView android:id="@+id/textScore" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="Your score:"
            android:paddingBottom="20dp" android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

        <TextView android:id="@+id/textHighScore"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:text="Highest score:" android:paddingBottom="20dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

        <Button android:id="@+id/button" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="Button"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content" android:layout_height="match_parent"
        app:menu="@menu/navigation_menu2" android:layout_gravity="start"
        android:id="@+id/nv2" app:headerLayout="@layout/navigation_header"
        app:itemIconTint="@drawable/tint_color_selector2">

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

最佳答案

你必须在从 intent 获取数据之前添加额外的内容。尝试将代码放在下面。

    Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
    accountActivity.putExtra("Score",somethingintscore)
    startActivity(accountActivity);

使用下面的代码获得额外的。

    Bundle bundle = getIntent().getExtras();
    if (bundle!=null && bundle.getInt("Score") > 0){
        score = bundle.getInt("Score");
        txtScore.setText("score" +score);
    }else
        txtScore.setText("score" + 0);

关于java - 在共享首选项上打开第二个 Activity/错误时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131807/

相关文章:

java - ensureCapacity 在 Java 中如何工作?

android - Glide 。缓存到外部存储(SD 卡)

java - 代码中的 MultiSelectListPreference

java - 在quartz中动态调度作业

java - 使用 GWT 读取剪贴板数据

java - 服务器通过网络使用Java序列化是否存在安全漏洞?

安卓屏幕方向 :

android - Youtube API key

Android Store 到外部或到 SharedPreferences

java - 如何使用 SharedPreferences 保存 arrayList<LatLng>