Here's the code. In this part, the answerIsTrue
variable should be initialized to true, which it rightly does (I debugged and checked) and is rightly also passed into putExtra() (again, I debugged and checked).
mCheatButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivity(i);
}
});
But coming to a different class, the variable mAnswerIsTrue
gets assigned to false (probably due to the default argument) despite the argument being passed by putExtra() is true. Here's the code.
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
I debugged this line as well, and it does get assigned to false. What could be wrong?
Here's the complete CheatActivity
class:
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
private Button mShowAnswerButton;
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mShowAnswerButton = (Button)findViewById(R.id.showAnswerButton);
mShowAnswerButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if (mAnswerIsTrue){
mAnswerTextView.setText(R.id.true_button);
}else{
mAnswerTextView.setText(R.id.false_button);
}
}
});
}
}
Note: I'm a complete beginner, who just learnt debugging.
Every time you rotate your screen, you should call pullExtra method. I am learning Android as well, but it seems to me that everytime onCreate method is called, Android app forgets all information about intend.
My code for that parts looks like this:
...
Use instead of
.getBooleanExtra()
theintent.extras.get()
. So your code will same like this:You need to cast, if you want to use the variable as an boolean.
If you want to put more extra, you need make a Bundle:
In your
CheatActivity
initializemAnswerIsTrue
inonCreate()
like this:for getting the data use the code
in button click use the code
" Ctrl + B " to get in method in API. (android studio)
defaultValue the value to be returned if no value of the desired type is stored with the given name.
I cannot be sure, but my best guess that, getBooleanExtra() is not good. I suggest using simple getExtras and then getting your value.