-2

source code link, app flow architecture, 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. null receive debug image link,

I wanna pass those three datas (from MainActivity) to 3rd activity Recyclerview items.

ThirdActivity.kt

class ThirdActivity : AppCompatActivity() {

    private var binding: ActivityThirdBinding? = null
    var editText1 = ""
    var editText2 = ""
    var textView1 = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityThirdBinding.inflate(layoutInflater)
        val view = binding?.root
        setContentView(view)

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

        editText1 = sharedPreferences.getString("editText1", "").toString()
        editText2 = sharedPreferences.getString("editText2", "").toString()
        textView1 = sharedPreferences.getString("textView1", "").toString()
    }



    private fun setAdapter() {
        val listAdapter = RecyclerViewAdapter(textList())
        binding?.rvRecyclerView?.adapter = listAdapter
        binding?.rvRecyclerView?.layoutManager = LinearLayoutManager(this)
    }

    private fun textList(): ArrayList<MyData> {
        return arrayListOf(
            MyData(
                text = editText1
            ),
            MyData(
                editText2
            ),
            MyData(
                textView1
            )
        )
    }
}

RecyclerviewAdapter.kt

class RecyclerViewAdapter(private val list: ArrayList<MyData>) :
    RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_list_layout, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val model = list[position]
        holder.textView.text = model.text
    }

    override fun getItemCount(): Int {
        return list.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var textView: TextView = itemView.findViewById(R.id.tvTextOne)
    }
  • 1
    You can use shared preferences to achieve this. – sajidjuneja Jan 01 '23 at 07:21
  • already tried, it's not working – Sindhuja MK Jan 01 '23 at 10:54
  • SharedPreferences definitely works, show what you tried in the question. – Tyler V Jan 01 '23 at 23:50
  • Can you share how did you try SharedPreferences? – sajidjuneja Jan 02 '23 at 10:03
  • I added my source code in this edit, I deleted whatever I tried, if anyone knows please edit the repository – Sindhuja MK Jan 03 '23 at 04:02
  • you need to understand , how intent works across activities. This type of questions already have answered so many times.. – Noorul Jan 04 '23 at 04:11
  • Does this answer your question? [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Noorul Jan 04 '23 at 04:15
  • @Noorul No, I know how to pass data between one activity to another activity, But my question is I want a pass main activity data to 3rd activity recyclerview items, not a 2nd activity . I don't know how to pass main activity datas to 3rd activity inside recyclerview and without passing data in second activity. – Sindhuja MK Jan 04 '23 at 05:04
  • @Noorul 2nd Activity is just for intent passing just a midille activity. We don't pass any data there. I attached my source code link, App architecture and flow image link – Sindhuja MK Jan 04 '23 at 05:06
  • if activity a ,b and c , you want to pass data between a to c means, the only way to do it is through activity b. so you need to pass the data to b, then you pass the data to c. it is applicable if the data flow is Linear.(a->b->c). if b is not an intermediate, you can directly pass the data from a to c. you can do using Preference manager. but it is not advisable to do so. – Noorul Jan 04 '23 at 07:01
  • @Noorul If b is intermediate means can't we pass the data to c? – Sindhuja MK Jan 04 '23 at 11:07
  • pass it to b. then pass that data from b to c. that's. it. – Noorul Jan 05 '23 at 06:55
  • it is easy only. android is not that much complicated like other languages. – Noorul Jan 05 '23 at 06:55

2 Answers2

0

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)
  • This code does not show how user can send data from 1st activity to 3rd activity. Please explain how user can achieve this. – sajidjuneja Jan 02 '23 at 10:05
  • I don't get your question. What's not clear about it? Can you please refer to it – Mahmoud Abdallah Jan 02 '23 at 13:50
  • User has asked to send data from 1st activity to 3rd activity, not 2nd activity. In this code, data is sent from 1st activity to 2nd activity and not 3rd activity. If using intent you need to send data then again user need to send intent in 2nd activity and receive data in 3rd activity which will not be efficient or recommended approach. – sajidjuneja Jan 02 '23 at 14:26
  • @MahmoudAbdallah I added my Source code above. In my project I just created 3 Activities. MainActivity.kt I have two edit text and one textview. In Second Activity I simply created one button. In ThirdActivity I created recyclerview that contains one text three times. And i want to send the 1st Activity Three text to inside 3rd Activity Recyclerview, item.[1st edit text - 1st position, 2edit text - 2nd position, 3rd textview - 3rd position] – Sindhuja MK Jan 03 '23 at 04:41
  • @MahmoudAbdallah Continueee.... When user click main Activity button it should goes to 2nd activity. then click 2nd activity button goes to 3rd Activity at the same time it needs to pass 1st activity data to 3rd activity recyclerview item. MyData( "edit text data", ), MyData( "Edit text data", ), MyData( "Text view data", ), – Sindhuja MK Jan 03 '23 at 04:43
  • @sajidjuneja you're correct in 1st activity if we send the intent using mydata we are getting 2nd activity not the 3rd. Now I edit my question. I attached the source code link and the Exact app architecture image as a link – Sindhuja MK Jan 03 '23 at 10:08
  • This can be handled in many ways. It all depends on the data you want to send, if they data is big, if MyData class has more than a string variable then sending list of MyData class between activities is not a great option. Same for using shared preferences, you have to convert your class to string, save it then in 3rd activity convert it back to object. Another issues with shared preferences is your data size. If you have a list of MyClass it will become harder to keep track of your keys. For this scenarios a database is always the best option. – Mahmoud Abdallah Jan 03 '23 at 13:24
  • For simple data, like list of string you can use shared preferences as @sajidjuneja suggested. – Mahmoud Abdallah Jan 03 '23 at 13:27
0

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)
        }

declare these variables before onCreate()

var editText1 = ""
var editText2 = ""
var textView1 = ""

In your 3rd activity onCreate

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

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

Then use these values in MyData modal.

sajidjuneja
  • 184
  • 7
  • With this code 3rd Activity is not opening. It shows error. java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.passdatabetweenactivities/com.example.passdatabetweenactivities.ThirdActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference and – Sindhuja MK Jan 03 '23 at 18:51
  • Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ContextWrapper.getPackageName(ContextWrapper.java:145) at android.app.Activity.getLocalClassName(Activity.java:6574) at android.app.Activity.getPreferences(Activity.java:6618) at com.example.passdatabetweenactivities.ThirdActivity.(ThirdActivity.kt:25) – Sindhuja MK Jan 03 '23 at 18:51
  • I attached my error and debug image in above edit please check that one. in debug it passing null values. And I pushed my code to repository with your code – Sindhuja MK Jan 04 '23 at 04:05
  • You are declaring these values outside of onCreate(). I mentioned to put them in onCreate(). Modify your code. – sajidjuneja Jan 04 '23 at 05:48
  • 1st I gave like that, But I can't pass the variables(editText1, editText2, textView1) inside MyData class values-( MyData( "edit text data", ), MyData( "Edit text data", ), MyData( "Text view data", ),. that's why I gave outside onCreate() – Sindhuja MK Jan 04 '23 at 11:08
  • You need to create variables first and then initialise them with the intent data. Then you can use them as you want. – sajidjuneja Jan 04 '23 at 11:11
  • Edited answer. Modify and check your code. – sajidjuneja Jan 04 '23 at 11:35
  • thankyou for this edited answer. Now there is no error, no app crash. But In 3rd Activity I didn;t get output. Recyclerview is scrolling.But the textview is blank. – Sindhuja MK Jan 05 '23 at 05:43
  • Just call ````setAdapter()```` below ````textView1 = sharedPreferences.getString("textView1", "").toString()````. It will work. – sajidjuneja Jan 05 '23 at 05:49
  • If it worked for you consider marking as accepted. – sajidjuneja Jan 05 '23 at 06:04
  • Does it work for you? I believe it does. Then mark answer as accepted so that it can be useful for others. – sajidjuneja Jan 05 '23 at 09:16
  • Thank you so much @sajidjuneja. I got output. – Sindhuja MK Jan 05 '23 at 10:55
  • I have a another doubt. Can we achieve this only using Sharedpreference? Or is there any other way to achieve this. – Sindhuja MK Jan 05 '23 at 10:56