我正在尝试将变量mCurrentIndex保存到savedInstanceState捆绑包中,以便在旋转屏幕时不会重启我的应用程序。我应该如何将这个变量放入包中?每次尝试时,我都会不断得到一个空对象引用。这是我正在使用的当前代码:
基本上,我尝试使用onSaveInstanceState方法存储mCurrentIndex的值,然后在onCreate方法中检索该值。如果将saveInstanceState.putInt()放在onCreate方法中的任何位置,则会得到空对象引用。
package com.example.geoquiz;
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 QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_australia, true),
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),
};
public int mCurrentIndex = 0;
// ...
@Override
protected void onCreate(final 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);
//savedInstanceState.putInt("index", mCurrentIndex);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
//mCurrentIndex = currentIndex;
updateQuestion();
}
});
//savedInstanceState.putInt("index",mCurrentIndex);
updateQuestion();
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("index",mCurrentIndex);
}
private void updateQuestion() {
//mCurrentIndex = savedInstanceState.getInt("index");
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();
}
} // to close the entire class
答案 0 :(得分:0)
为了做到这一点而又没有空指针异常,您可以这样做:
if (savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt("index");
}
此外,onSavedInstanceState方法具有以下格式:
@Override
public void onSaveInstanceState(Bundle outState){
outState.putInt("index",mCurrentIndex);
super.onSaveInstanceState(outState);
}