mTrueButton is nil


#1

Using Android Studio, instead of ADT, but still, I’m not seeing what’s wrong here:

fragment_quiz.xml:

... <Button android:id="@+id/true_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/true_button"/>

R.java:

public static final class id { ... public static final int true_button=0x7f07003d; ...

QuizActivity.java:

public class QuizActivity extends ActionBarActivity { private Button mTrueButton, mFalseButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); mTrueButton = (Button)findViewById(R.id.true_button); ...

mTrueButton is nil. (Likewise for mFalseButton.)

What am I missing here? I’m assuming something to do with using “fragment_quiz.xml” instead of “activity_quiz.xml”, but not sure if that’s a difference between ADT-v-AS, or because of using a later SDK.

Help?


#2

Answering my own question here (after reading ahead in the book), for posterity and closure.

I figured out I needed to move stuff into PlaceholderFragment, onCreateView():

	public static class PlaceholderFragment extends Fragment {

		private Button mTrueButton, mFalseButton;

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
		                         Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_quiz, container, false);

			mTrueButton = (Button)rootView.findViewById(R.id.true_button);
			mTrueButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(PlaceholderFragment.this.getActivity(), R.string.incorrect_toast, Toast.LENGTH_SHORT).show();
				}
			});
...

Thanks! :wink:
randy