I am developing an app for a survey service.
The user must enter their country in order to sign up.
I am using an alertDialog
using radio buttons
.
Here is my java code:
public void onClickCountrySCI(View view) {
final String[] CategorySelected = {null};
final String categories[] = {"USA", "Mexico", "Canada"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Country:");
builder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
CategorySelected[0] = categories[i];
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (CategorySelected[0].equals("USA")) {
et4.append(categories[i]);
} else if (CategorySelected[1].equals("Mexico")) {
et4.append(categories[i]);
} else if (CategorySelected[2].equals("Canada")) {
et4.append(categories[i]);
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
builder.show();
}
I keep getting an error. It is
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
How can I get rid of this? Thanks in advance.
EDIT UPDATED CODE
public void onClickCountrySCI(View view) {
final String[] CategorySelected ={""};
final String categories[] = {"USA", "Mexico", "Canada"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Country:");
builder.setSingleChoiceItems(categories, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
CategorySelected[0] = categories[i];
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (CategorySelected.equals("USA")) {
et4.append(categories[i]);
} else if (CategorySelected.equals("Mexico")) {
et4.append(categories[i]);
} else if (CategorySelected.equals("Canada")) {
et4.append(categories[i]);
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
builder.show();
}
Here is my updated code.
Here is my EditText XML:
<EditText
android:onClick="onClickCountrySCI"
android:focusable="false"
android:inputType="text"
android:layout_marginTop="10dp"
android:layout_marginStart="15dp"
android:layout_below="@+id/et_fourteen_sci"
android:id="@+id/et_fifteen_sci"
android:hint="Country"
android:textColor="@color/colorAccent"
android:backgroundTint="@color/colorPrimary"
android:layout_width="330dp"
android:layout_height="45dp" />
This is all my updated code.
I don't get errors no more, but the radio button values are being placed to the EditText.