Home > Blockchain >  Kotlin - Calling a function or adding a data into ArrayList form another activity
Kotlin - Calling a function or adding a data into ArrayList form another activity

Time:10-09

I want to make 2 activities called Activity A and Activity B.

Inside Activity A, I want a RecyclerView that is filled by an ArrayList variable named arrName with zero data inside it the first time it launches.

Inside Activity B, I want an EditText and a Button to let user input a name and store it into arrName.

How would I do the data input from Activity B into arrName?

CodePudding user response:

You can do this simply by using companion object.

You initialize your ArrayList<String> inside your companion object. You also make a function inside your companion object to add a value inside that ArrayList.

Here is the example code of Activity A:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    companion object{
        val arrName: ArrayList<String> = arrayListOf()
        
        fun addName(name: String){
            arrName.add(name)
        }
    }
}

And you simply call the addName(name) from Activity B by using this code:

MainActivity.addName("Berlin")
  • Related