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>
4
  • 1
    Does this answer your question? Loop through all subviews of an Android view? Commented Jul 2, 2021 at 14:26
  • I am looking for Kotlin. Commented Jul 2, 2021 at 14:35
  • Can you share the layout Commented Jul 2, 2021 at 14:48
  • Code updated in the question. Commented Jul 2, 2021 at 14:58

2 Answers 2

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
    }
    
}
Sign up to request clarification or add additional context in comments.

20 Comments

@Codist Please check UPDATE section in the answer
This is right.. Or you can use the databinding one binding.rootw object directly
Yes they are TextInputEditText .. Already handled that in code
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
Wow..Good job! just didn't notice that you used customized EditText .. I just updated it now
|
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
}

1 Comment

There is some error. I have added the error and complete code the Kotlin file in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.