没有此类实例字段

2022-09-02 14:21:19

我正在尝试让我的应用程序在屏幕方向更改时使用保存布尔值保存一些数据。onSaveInstanceStatemCheated

我设置了许多断点,但在变量视图中收到布尔值的错误mCheated

mCheated= No such instance field: 'mCheated'

我不知道为什么,因为我在活动启动时用值false声明它,如果按下按钮,则将其更改为true。任何人都可以帮我吗?

package com.bignerdranch.android.geoquiz;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Chris on 20/02/2015.
 */
public class CheatActivity extends Activity {

    public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
    public static final String EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";

    private static final String KEY_INDEX = "index";

    private boolean mAnswerIsTrue;

    private TextView mAnswerTextView;
    private Button mShowAnswer;

    private boolean mCheated = false;

    private void setAnswerShownResult(boolean isAnswerShown) {
        Intent data = new Intent();
        data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
        setResult(RESULT_OK, data);
    }

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

        mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,false);

        if (savedInstanceState != null){
            mCheated = savedInstanceState.getBoolean(KEY_INDEX, mCheated);
        }
        setAnswerShownResult(mCheated);

        mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
        mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
        mShowAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAnswerIsTrue) {
                    mAnswerTextView.setText(R.string.true_button);
                }
                else {
                    mAnswerTextView.setText(R.string.false_button);
                }
                setAnswerShownResult(true);
                mCheated = true;
            }
        });

    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        //Log.i(TAG, "onSaveInstanceState");
        savedInstanceState.putBoolean(KEY_INDEX, mCheated);
    }
}

答案 1

事实证明,代码没有问题,Android Studio需要重新启动。我认为这归因于我已经克隆了该项目,并且可能使用了以前版本中的错误文件。


答案 2

检查您在 Android Studio 中的构建变体是否具有

  • 可调试为真
  • proguard 被禁用或注释掉。