I want to add the dynamic checkbox in linear layout and the checkbox should become according to the size of JSON array from API.
my API response is like that :
[ { "id": 1, "alertName": "Device" }, { "id": 2, "alertName": "Email" } ]
I want to add the dynamic checkbox in linear layout and the checkbox should become according to the size of JSON array from API.
my API response is like that :
[ { "id": 1, "alertName": "Device" }, { "id": 2, "alertName": "Email" } ]
 
    
     
    
    Super Easy!
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rooView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"/>
item_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
    android:id="@+id/checkbox"
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var jsonArray = getJsonArray()
        for (i in 0 until jsonArray.length()) {
            var checkBox = LayoutInflater.from(this)
                .inflate(R.layout.item_checkbox, rooView, false) as CheckBox
            checkBox.text = jsonArray[i].toString()
            rooView.addView(checkBox)
        }
    }
    private fun getJsonArray(): JSONArray {
        var jsonObject: JSONObject = JSONObject()
        var jsonArray = JSONArray()
        jsonArray.put("Charlie")
        jsonArray.put("Buddy")
        jsonArray.put("Oscar")
        jsonArray.put("Milo")
        jsonArray.put("Archie")
        jsonArray.put("Ollie")
        jsonObject.put("pets", jsonArray)
        return jsonArray
    }
    }
