0

I have ten ExitText and I want to add its value into an ArrayList and then add them to Firebase.

How can I add the values into an ArrayList in Kotlin?

I know this is not how it should be done, but I was just trying and I was stuck at looping through and add to the array. I know I can use zipCodeList.add to add, but I do not know how to loop through the EditTexts and get value.

fun createListOfZipCodes (): ArrayList<ZipCode>{
    
            zip_one=binding.etZipCodeOne.text.toString()
            zip_two=binding.etZipCodeTwo.text.toString()
            zip_three=binding.etZipCodeThree.text.toString()
            zip_four=binding.etZipCodeFour.text.toString()
            zip_five=binding.etZipCodeFive.text.toString()
            zip_six=binding.etZipCodeSix.text.toString()
            zip_seven=binding.etZipCodeSeven.text.toString()
            zip_eight=binding.etZipCodeEight.text.toString()
            zip_nine=binding.etZipCodeNine.text.toString()
            zip_ten=binding.etZipCodeTen.text.toString()
    
    /// I HAVE NO IDEA HOW TO LOOP THROUGH EACH EDIT TEXT AND GET THE VALUE.
    
            return zipCodeList
    
}

I am looking for an answer to do this in Kotlin.

Thank you.


Edit 2

class AssignZIPCodeActivity : AppCompatActivity() {
    
        private lateinit var binding:ActivityAssignZipcodeBinding
    
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
            setContentView(binding.root)
            
            }
    
    }

EDIT:

Error

    2021-07-02 21:08:30.525 21588-21588/com.trad E/RecyclerView: No adapter attached; skipping layout
2021-07-02 21:08:35.505 21588-21588/com.trad E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.trad, PID: 21588
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.trad/com.trad.ui.activities.AssignZIPCodeActivity}: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3683)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8512)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at com.trad.ui.activities.AssignZIPCodeActivity.<init>(AssignZIPCodeActivity.kt:18)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3671)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:246) 
        at android.app.ActivityThread.main(ActivityThread.java:8512) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) 

Complete Kotlin code.

    class AssignZIPCodeActivity : AppCompatActivity() {

    private lateinit var binding:ActivityAssignZipcodeBinding
    private lateinit var zipCodeList:ArrayList<String>

     val fields = listOf(
        binding.etZipCodeOne,
        binding.etZipCodeTwo,
        binding.etZipCodeThree,
        binding.etZipCodeFour,
        binding.etZipCodeFive,
        binding.etZipCodeSix,
        binding.etZipCodeSeven,
        binding.etZipCodeEight,
        binding.etZipCodeNine,
        binding.etZipCodeTen,
    )

    val zipCodes = createListOfZipCodes(fields)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnAddZipCodes.setOnClickListener{
            createListOfZipCodes(fields)
//            Toast.makeText(this@AssignZIPCodeActivity,zipCodeList.toString(),Toast.LENGTH_SHORT).show()
        }
    }

Following is the activity_assign_zipcode.xml.

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.AssignZIPCodeActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="none">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_one"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 1"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize"/>
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_two"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_one"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 2"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_three"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_two"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 3"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_three"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_four"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_three"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 4"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_four"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_five"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_four"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 5"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_five"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_six"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_five"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 6"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_six"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_seven"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_six"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 7"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_seven"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_eight"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_seven"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 8"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_eight"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_nine"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_eight"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 9"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_nine"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_ten"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_nine"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 10"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_ten"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.trad.utils.MSPButton
                android:id="@+id/btn_add_zip_codes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginStart="16dp"
                android:layout_marginTop="30dp"
                android:layout_marginEnd="16dp"
                android:background="@drawable/button_background"
                android:foreground="?attr/selectableItemBackground"
                android:gravity="center"
                android:paddingTop="@dimen/btn_padding"
                android:paddingBottom="@dimen/btn_padding"
                android:text="@string/btn_lbl_submit"
                android:textColor="@android:color/white"
                android:textSize="@dimen/btn_textSize"
                android:layout_below="@id/til_zip_code_ten"/>
        </RelativeLayout>

    </ScrollView>

</RelativeLayout>
Zain
  • 37,492
  • 7
  • 60
  • 84
Codist
  • 737
  • 8
  • 23

2 Answers2

1

This is not the same duplicate as pointed out. The OP requires to have a nicer way of adding elements into an array without dealing with their ids.

So, give an id for the RelativeLayout that holds the EditText's:

    <RelativeLayout
        android:id="@+id/root"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

Then you can iterate over the children of the RelativeLayout and find TextInputLayout. And repeat to find the TextInputEditText

val list = arrayListOf<String>()

// Layout that has multiple TextInputLayouts
val root = findViewById<RelativeLayout>(R.id.root)

// Iterating over children of the RelativeLayout
for (item in 0..root.childCount) {
    val child = root.getChildAt(item)
    if (child is TextInputLayout) {
        val editText = (child.getChildAt(0) as FrameLayout).getChildAt(0)
        if (editText is TextInputEditText) list.add(editText.text.toString())
    }
}
Log.d(TAG, "onCreate: $list")

UPDATE:

How can I write this as a function so that I can call it on a button click?

class AssignZIPCodeActivity : AppCompatActivity() {

    private lateinit var binding:ActivityAssignZipcodeBinding
    private lateinit var zipCodeList:ArrayList<String>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        binding.btnAddZipCodes.setOnClickListener{
              zipCodeList = createListOfZipCodes()

//            Toast.makeText(this@AssignZIPCodeActivity,zipCodeList.toString(),Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun createListOfZipCodes(): ArrayList<String> {
    
        val list = arrayListOf<String>()

        // Layout that has multiple TextInputLayouts
        val root = findViewById<RelativeLayout>(R.id.root)

        // Iterating over children of the RelativeLayout
        for (item in 0..root.childCount) {
            val child = root.getChildAt(item)
            if (child is TextInputLayout) {
                val editText = (child.getChildAt(0) as FrameLayout).getChildAt(0)
                if (editText is com.trad.utils.MSPEditText) list.add(editText.text.toString())
            }
        }   
        return list
    }
    
}
Zain
  • 37,492
  • 7
  • 60
  • 84
  • How can I write this as a function so that I can call it on a button click? Under Edit 2 in my question, I have added my simple and code. – Codist Jul 02 '21 at 19:39
  • 1
    @Codist Please check UPDATE section in the answer – Zain Jul 02 '21 at 20:15
  • There are no errors, but unfortunately, toast after `zipCodeList = createListOfZipCodes()` shows just []. – Codist Jul 02 '21 at 20:46
  • @Codist Have you added something in the EditText fields? – Zain Jul 02 '21 at 20:50
  • I added numbers. – Codist Jul 02 '21 at 20:50
  • Just to make sure, Is that the Toast of `Toast.makeText(this@AssignZIPCodeActivity,zipCodeList.toString(),Toast.LENGTH_SHORT).show()` That you commented out just after `zipCodeList = createListOfZipCodes()` line – Zain Jul 02 '21 at 20:55
  • Yes, that is the Toast. – Codist Jul 02 '21 at 20:58
  • I wish I could help .. Believe me I tested this out before submitting it.. No problem for me If you would like to share some sample project, so that I can reproduce this issue especially it didn't raise errors with you. – Zain Jul 02 '21 at 21:00
  • `android:id="@+id/rootw"` is the id I have given to the `RelativeLayout` that contain the `EditTexts`s. Accordingly I changed your `val root = findViewById(R.id.root)` to `val root = findViewById(R.id.rootw)`. That is the only change I made to your code. – Codist Jul 02 '21 at 21:02
  • 1
    This is right.. Or you can use the databinding one `binding.rootw` object directly – Zain Jul 02 '21 at 21:03
  • Changed but, no avail. – Codist Jul 02 '21 at 21:07
  • Could you take a look at my `XML` code which I have already provided. The `EditText`s are not ordinary `ExitText`s. Is that OK? – Codist Jul 02 '21 at 21:13
  • 1
    Yes they are `TextInputEditText` .. Already handled that in code – Zain Jul 02 '21 at 21:14
  • Could you check if we have initialized `zipCodeList` correctly? – Codist Jul 02 '21 at 21:28
  • 1
    Can you change this `if (editText is TextInputEditText) list.add(editText.text.toString())` to `if (editText is com.trad.utils.MSPEditText) list.add(editText.text.toString())` in my code – Zain Jul 02 '21 at 21:36
  • So, that was the culprit. It's now working. Thank you so much. – Codist Jul 02 '21 at 21:43
  • I shall mark your response as the answer once you update it in there. – Codist Jul 02 '21 at 21:45
  • 1
    Wow..Good job! just didn't notice that you used customized `EditText` .. I just updated it now – Zain Jul 02 '21 at 21:46
  • 1
    Hats off. You are one in a million who really want to help. Some are after earning the reputation. :)) – Codist Jul 02 '21 at 21:47
  • Can you check this out? https://stackoverflow.com/q/68199385/13935956 – Codist Jul 03 '21 at 05:05
0

Hard to do much better:

val fields = listOf(
        binding.etZipCodeOne,
        binding.etZipCodeTwo,
        binding.etZipCodeThree,
        binding.etZipCodeFour,
        binding.etZipCodeFive,
        binding.etZipCodeSix,
        binding.etZipCodeSeven,
        binding.etZipCodeEight,
        binding.etZipCodeNine,
        binding.etZipCodeTen,
)

val zipCodes = createListOfZipCodes(fields)

fun createListOfZipCodes(fields: List<EditText>): ArrayList<ZipCode> {
    val zipCodeList = mutableListOf<ZipCode>()
    for (filed in fields) {
        zipCodeList.add(filed.text.toString())
    }
    return zipCodeList
}
Yavor Mitev
  • 1,363
  • 1
  • 10
  • 22
  • There is some error. I have added the error and complete code the Kotlin file in the question. – Codist Jul 02 '21 at 15:48