Taha
Taha

Reputation: 65

App crashing when adding getCheckedRadioButtonId()

I have a navigation activity made up of fragments, and I have a button that is attached to an onClickListener, which runs the onClick method. The app opens normally and so does the fragment, but whenever I click the button, the app crashes

public class FirstFragment extends Fragment implements View.OnClickListener {

View myView;

private RadioGroup radioGroup;
private Button btnDisplay;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.first_layout, container, false);
    btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
    return myView;
}

@Override
public void onClick(View v) {
    radioGroup = (RadioGroup) v.findViewById(R.id.radio);

    int selectedId = radioGroup.getCheckedRadioButtonId();
    }
}

Through some testing, I found that this line was causing an issue. I need this line because I want to pass selectedId into a radiobutton

int selectedId = radioGroup.getCheckedRadioButtonId();

Without this line, the app and fragment open normally, and the app doesn't crash when the button is clicked, I added a toast, and it worked fine without the line of code above. Could anyone explain how to fix this? Thank you

Upvotes: 1

Views: 321

Answers (2)

Oleg
Oleg

Reputation: 206

find your RadioGroup not in view that was clicked but in root view of the fragment, so this line:

radioGroup = (RadioGroup) v.findViewById(R.id.radio);

change to this:

radioGroup = (RadioGroup) myView.findViewById(R.id.radio);

hope it helps...

Upvotes: 1

Quick learner
Quick learner

Reputation: 11477

Put this line in onCreateview

radioGroup = (RadioGroup) v.findViewById(R.id.radio);

Like this

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.first_layout, container, false);
     radioGroup = (RadioGroup) myView .findViewById(R.id.radio);
    btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
    return myView;
}

Upvotes: 1

Related Questions