getBooleanExtra() using only the default argument and not the one passed by putExtra()
19,984
I cannot be sure, but my best guess that, getBooleanExtra() is not good. I suggest using simple getExtras and then getting your value.
i.putExtra(EXTRA_ANSWER_IS_TRUE, value);
Bundle args = MyActivity.getIntent().getExtras();
boolean istrue= args.getBoolean(EXTRA_ANSWER_IS_TRUE, false);
Author by
Slay
Updated on June 14, 2022Comments
-
Slay almost 2 years
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.
-
Slay almost 10 yearsmAnswerIsTrue was actually always declared inside onCreate. Still doesn't work. I misunderstood your question interpreting you were asking about EXTRA_ANSWER_IS_TRUE being inside onCreate(), which isn't(obviously). Sorry about that. Anyways, it still doesn't work. Anything else that could be going wrong?
-
Slay almost 10 yearsNo. Problem still persisting.
-
Nithinlal almost 10 yearstry this and tell me what u got?
-
Slay almost 10 yearsI've already debugged, and the value passed is true. Here's where it becomes false:
mAnswerIsTrue = getIntent().getBooleanExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, false);
. Check the code in he description for further context.