0

How to correctly transfer data from a fragment to an activity? I do as follows: 1- Create an interface

interface IProfileToActivity {
    fun profileInfo(data: AllHeroes.Global)
}

2- Then I inheritance in the activity

class ProfileActivity : AppCompatActivity(), IProfileToActivity {
private lateinit var myBinding: ActivityProfileBinding
    override fun profileInfo(data: AllHeroes.Global) {
        myBinding.tvUsername.text = data.name
        myBinding.tvDivision.text = data.rank.rankName
        Log.i("Apex Info 3", data.toString())
    }
}

3- sending from a fragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
  (activity as? IProfileToActivity)?.profileInfo(allInfoApexResponse.global)
                mHeroesAdapter.heroesList(allAdapterListHero)
}

but nothing happens, why? what did I do wrong?

Ethernets
  • 201
  • 2
  • 12

2 Answers2

4

You need not create an interface here. You can use requireActivity() to get a reference to the parent activity. Using it you can access public fields and functions of you activity.

class ProfileActivity : AppCompatActivity() {
    
    private lateinit var myBinding: ActivityProfileBinding

    fun profileInfo(data: AllHeroes.Global) {
        myBinding.tvUsername.text = data.name
        myBinding.tvDivision.text = data.rank.rankName
        Log.i("Apex Info 3", data.toString())
    }
}

And in your fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    (requireActivity as ProfileToActivity).profileInfo(allInfoApexResponse.global)
    mHeroesAdapter.heroesList(allAdapterListHero)
}
Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40
  • 2
    i got error ```java.lang.ClassCastException: com.example.apextracker.view.activities.MainActivity cannot be cast to com.example.apextracker.view.activities.ProfileActivity``` i think this is due to the fact that ProfileActivity is not a parent of the fragment – Ethernets Nov 04 '21 at 09:01
  • So, the parent of your fragment is MainActivity but you want to send data to ProfileActivity. Is it so? – Arpit Shukla Nov 04 '21 at 09:03
  • Yes that's right – Ethernets Nov 04 '21 at 09:03
  • Where is Profile Activity? Is it in the back stack? – Arpit Shukla Nov 04 '21 at 09:04
  • ProfileActivity is a separate activity from a fragment, which is launched when the menu is called ```override fun onOptionsItemSelected (item: MenuItem): Boolean { when (item.itemId) { R.id.action_profile -> { (requireActivity () as ProfileActivity) .profileInfo (testApex) startActivity (Intent (requireActivity (), ProfileActivity :: class.java)) return true } } return super.onOptionsItemSelected (item) }``` – Ethernets Nov 04 '21 at 09:08
  • and in this separate activity me need to transfer the data pool – Ethernets Nov 04 '21 at 09:10
  • So what you want is to launch a new activity (ProfileActivity) when user selects "Profile" from overflow menu, and you want to pass some data to that ProfileActivity at the same time. RIght? – Arpit Shukla Nov 04 '21 at 09:10
1

There are many ways to pass data from fragment to activity:

Using shared ViewModel.

A ViewModel is used to manage and store UI related data in a lifecycle conscious way. ~Read more

class SharedViewModel: ViewModel() {

    private val currItems: MutableLiveData<List<Item>> =
        MutableLiveData<List<Item>>(listOf())

    fun getCurrItem(): LiveData<List<Item>> {
        return currItems
    }

    fun sendCurrItems(items: MutableList<Item>) {
        currItems.postValue(items)
    }
}
class ItemFragment: Fragment() {
    private val sharedModel: SharedViewModel by activityViewModels()
}

MainActivity: AppCompactActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val model = ViewModelProvider(this).get(SharedViewModel::class.java)
    }
}

In the above class, data is being stored and updated using an MutableList. Thing to be noted here is, the above class is a singleton class, i.e. once it is created, it gets destroyed only when the activity is ended.

Let us assume that an item has to be shared from a ItemFragment to the MainActivity

One callback has to be implemented the MainActivity. For that, one can use an Interface

interface ItemListener{
    fun sendItem(item : MutableList<Item>)
}

ItemFragment:

class ItemFragment: Fragment() {
   
   override fun sendItems(items: MutableList<Item>?) {
        // Send an Item from here as well as update it
    }
    // Or just simply call sendItem method.
} 

MainActivity:

class MainActivity: AppCompactActivity(){
    
    fun receiveItem(context : Context){
       
      private var mCallback: ItemListener? = null
      mCallback = context
     }

}
Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24