Dynamically Add Radio Buttons to Android Studio Activity


I am trying to create an app with some dynamic survey questions in Android Studio with Java. The user is providing a list of strings, and I want that list to display as radio buttons. My code currently in my CreditForWhat.java file is

public class CreditForWhat extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        RadioGroup allButtons = findViewById(R.id.categoryGroup);
        String[] categories = new String[] {"Task 1", "Task 2", "Task 3", "Task 4"};

        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_credit_for_what);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        addRadioButtons(categories, allButtons);
    }

    public void addRadioButtons(String[] list, RadioGroup buttons) {
        int number = list.length;
        for (int i = 0; i < number; i++) {
            String category = list[i];
            RadioButton rdbtn = new RadioButton(this);
            rdbtn.setId(View.generateViewId());
            rdbtn.setText(category);
            buttons.addView(rdbtn, i);
        }
    }
}

The idea is that the list is provided in one activity and displayed in another. I had the button set up in the main activity such that the static list would appear, so I know that is set up correctly. Now that I removed the static buttons and tried to set up this dynamic loop, the app crashes if I hit the button to try and open this activity.

My troubleshooting determined that

buttons.addView(rdbtn, i);

is the line that is causing the crash. The error message in Logcat says

Failed to execute the transaction: tId:-591813127 ClientTransaction{
                                                                                                    tId:-591813127   transactionItems=[
                                                                                                    tId:-591813127     LaunchActivityItem{activityToken=android.os.BinderProxy@ddd3d44,intent=Intent { xflg=0x4 cmp=com.example.earnedit/.CreditForWhat },ident=26557374,info=ActivityInfo{43ddc9b com.example.earnedit.CreditForWhat},curConfig={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0},overrideConfig={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.2 fontWeightAdjustment=0},deviceId=0,referrer=com.example.earnedit,procState=2,state=null,persistentState=null,pendingResults=null,pendingNewIntents=null,sceneTransitionInfo=null,profilerInfo=null,assistToken=android.os.BinderProxy@e3b534c,shareableActivityToken=android.os.BinderProxy@b6bcf95,activityWindowInfo=ActivityWindowInfo{isEmbedded=false, taskBounds=Rect(0, 0 - 1080, 2400), taskFragmentBounds=Rect(0, 0 - 1080, 2400)},displayId=0}
                                                                                                    tId:-591813127     ResumeActivityItem{mActivityToken=android.os.BinderProxy@ddd3d44,procState=-1,isForward=true,shouldSendCompatFakeFocus=false}
                                                                                                    tId:-591813127     Target activity: com.example.earnedit.CreditForWhat
                                                                                                    tId:-591813127   ]
                                                                                                    tId:-591813127 }
2026-07-19 23:35:53.949 15429-15429 AndroidRuntime          com.example.earnedit                 D  Shutting down VM
2026-07-19 23:35:53.955 15429-15429 AndroidRuntime          com.example.earnedit                 E  FATAL EXCEPTION: main
                                                                                                    Process: com.example.earnedit, PID: 15429
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.earnedit/com.example.earnedit.CreditForWhat}
                                                                                                    	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4496)
                                                                                                    	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4699)
                                                                                                    	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:224)
                                                                                                    	at android.app.servertransaction.TransactionExecutor.executeNonLifecycleItem(TransactionExecutor.java:133)
                                                                                                    	at android.app.servertransaction.TransactionExecutor.executeTransactionItems(TransactionExecutor.java:103)
                                                                                                    	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:80)
                                                                                                    	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2961)
                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:132)
                                                                                                    	at android.os.Looper.dispatchMessage(Looper.java:333)
                                                                                                    	at android.os.Looper.loopOnce(Looper.java:263)
                                                                                                    	at android.os.Looper.loop(Looper.java:367)
                                                                                                    	at android.app.ActivityThread.main(ActivityThread.java:9287)
                                                                                                    	at java.lang.reflect.Method.invoke(Native Method)
                                                                                                    	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:566)
                                                                                                    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.addView(android.view.View, int)' on a null object reference
                                                                                                    	at com.example.earnedit.CreditForWhat.addRadioButtons(CreditForWhat.java:48)
                                                                                                    	at com.example.earnedit.CreditForWhat.onCreate(CreditForWhat.java:35)
                                                                                                    	at android.app.Activity.performCreate(Activity.java:9306)
                                                                                                    	at android.app.Activity.performCreate(Activity.java:9284)
                                                                                                    	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1541)
                                                                                                    	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4480)
                                                                                                    	... 14 more

Everything I have seen about this topic says the addView is the correct call for this task. Is that no longer the case?

In the final version, I want the category selection to bring up a different variable list of fields, depending on the category, so I need to understand how to create these dynamic fields.

1
Jul 20 at 5:23 AM
User AvatarHannah Laskey
#java#android#radio-button#dynamic-programming

Accepted Answer

Yes, you are right - addView() is correct. I see that the crash happens because you call findViewById() before setContentView(). You need to do opposite - you need to move up and call setContentView() before findViewById() and the error will be gone.

User AvatarDeividas Strole
Jul 21 at 3:35 AM
0