Home > front end >  Pass textview data from Main Activity to 3rd Activity recyclerview Kotlin Android
Pass textview data from Main Activity to 3rd Activity recyclerview Kotlin Android

Time:01-04

In MainActivity I have 2 edit text and one textView. In 2nd Activity I have a viewpager image slider. 3rd activity I ceated recyclerview that contains 3 items.

private fun namelist(): ArrayList<MyData> {
        return arrayListOf(
            MyData(
                "edit text data",      
            ),
            MyData(
                "Edit text data",
            ),
           
            MyData(
                "Text view data",
            ),
        )
    }
I wanna pass those three datas (from MainActivity) to 3rd activity Recyclerview items.

[Source code here][2]


  [App flow image link]: https://i.stack.imgur.com/fsfgI.png


  [source code link]: https://github.com/sindhujaMK/PassDataBetweenActivities

CodePudding user response:

First, make sure MyData class is Parcelable.

Then when you create an intent to navigate to the other activity add array of MyData to it. Like this

val intent = Intent(this, <OtherActivity>)
intent.putParcelableArrayListExtra(<someKey>, arrayListOf(myData1, myData2))
startActivity(intent)

Then in your other activity get data like this

val myDataList = intent.getParcelableArrayListExtra<MyData>(<someKey>)

Note that you might get deprecation error on this line of code. It was deprecated in android 33 for more type-safety

This is the new way of getting data

val myDataList = intent.getParcelableArrayListExtra(<someKey>, MyData::class.java)

CodePudding user response:

In your MainActivity 1

val sharedPreferences: SharedPreferences =
            getSharedPreferences("MySharedPref", MODE_PRIVATE)

        val myEdit = sharedPreferences.edit()

        binding?.btnButton?.setOnClickListener {
        myEdit.putString("editText1", editText1.getText().toString())
        myEdit.putString("editText2", editText2.getText().toString())
        myEdit.putString("textView1", textView1.getText().toString())

        myEdit.apply()
        val intent = Intent(this@MainActivity, SecondActivity::class.java)
            startActivity(intent)
        }

In your 3rd activity onCreate

val sharedPreferences: SharedPreferences =
            getSharedPreferences("MySharedPref", MODE_PRIVATE)

val editText1 = sharedPreferences.getString("editText1", "")
val editText2 = sharedPreferences.getString("editText2", "")
val textView1 = sharedPreferences.getString("textView1", "")

Then use these values in MyData modal.

  • Related