So what i want is to launch a new activity (ProfileActivity) when user selects "Profile" from overflow menu, and i want to pass some data to that ProfileActivity at the same time. How to properly transfer data from a fragment to another activity that is not a container of the fragment itself? I do the following:
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)
}
The data should be transferred to another activity after clicking the Profile button in the menu
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.action_profile -> {
(activity as? IProfileToActivity)?.profileInfo(testApex)
startActivity(Intent(requireActivity(), ProfileActivity::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
but nothing happens, why? what did I do wrong?
CodePudding user response:
if you're routing from fragment to another activity, you can put you data into the intent using the putExtra
and then receive in the activity using getExtra
.
Inside the fragment,
Intent profileActivityIntent = new Intent(context,ProfileActivity.class);
profileActivityIntent.putExtra("dataKey",data);
startActivity(profileActivityIntent);
And then inside the ProfileActivity's onCreate
method,
//assuming that data is a string
String dataFromFragment = getIntent().getStringExtra("dataKey");
Log.i("Data from fragment",dataFromFragment);
You are in no need of using the interface method. (If you have to route from one fragment to activity).
If your requirement is different, please let me know in the comments.