I want to retrieve a value from a text of a radiobutton inside a radiogroup. This sounds really simple but I am not being able to put it to work as it always gives me a null value.
Here is my code:
public class NewMovie extends FragmentActivity {
RadioGroup rating;
RadioButton selectedRating;
int selectedRatingIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_movie_layout);
rating = (RadioGroup) findViewById(R.id.rating);
onClickListenerButton();
}
public void onClickListenerButton()
{
selectedRatingIndex = rating.getCheckedRadioButtonId();
final RadioButton selectedRating = (RadioButton) findViewById(selectedRatingIndex);
intent.putExtra("rating", selectedRating.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
XML:
<RadioButton
android:id="@+id/U"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/U" />
<RadioButton
android:id="@+id/PG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/PG" />
<RadioButton
android:id="@+id/r12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/r12" />
<RadioButton
android:id="@+id/r15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/r15" />
<RadioButton
android:id="@+id/r18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/r18" />
</RadioGroup>
Always nullpointerexception for some reason.
Don't know if it helps the context, but I am trying to go from activity 1 to activity 2, in activity 2 (the one I show above) display the radiogroup and the user then submits one of the answers and the answer is then used in activity 1.
You have to put a default select in radio buttons, Try as follow,
Place all your radio buttons with in radio group in xml
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/U"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/U"
android:checked="true" /> // deafult select
//other radio buttons
</RadioGroup>
Initiate all radio buttons in activity
radioU=(RadioButton) findViewById(R.id.U);
Check the selection in button click event
public void onClickListenerButton(View v) {
if(radioU.isChecked())
{
intent.putExtra("rating", getResources().getString(R.string.U));
}
else if(radioPG.isChecked())
{
intent.putExtra("rating", getResources().getString(R.string.PG));
}
setResult(RESULT_OK, intent);
finish();
}