简体   繁体   中英

How to send data from fragment to Activity in Android

In my application i want use Fragment and Activity and i want startActivity from this fragment and i should send data with startActivity
I write below codes, but when running application show null in activity !
Fragment codes :

homeDashboard_giftInfoLayout.setOnClickListener {
    val intent = Intent(requireContext(), DashboardChargeWalletActivity::class.java)
    intent.putExtra(USER_WALLET_PRICE, response.user.wallet.credit)
    intent.putExtra(USER_CHARGED_VALUE, 0)
    startActivity(intent)
}

Activity codes :

userWallet = intent?.getStringExtra(USER_WALLET_PRICE).toString()
userWallet.let {
    //User wallet
    dashboardChargeWallet_userWallet.text =
        "${getString(R.string.walletInventory)}: $userWallet ${getString(R.string.toman)}"
}

when click on button for startActivity i show this response.user.wallet.credit into toast .
But into activity show me null !

I used Kotlin for language.

How can i fix it?

you need to use intent like this from a fragment.

homeDashboard_giftInfoLayout.setOnClickListener {
 val intent = Intent(activity, DashboardChargeWalletActivity::class.java)
 intent.putExtra(USER_WALLET_PRICE, response.user.wallet.credit)
 intent.putExtra(USER_CHARGED_VALUE, 0)
 startActivity(intent);
}

also you can use requireActivity

val intent=Intent(requireActivity(),DashboardChargeWalletActivity::class.java)

Hopefully this will work for you.

this line:

intent.putExtra(USER_WALLET_PRICE, response.user.wallet.credit)

I suspect that response.user.wallet.credit isn't a string. So the below line:

userWallet = intent?.getStringExtra(USER_WALLET_PRICE).toString()

won't find a string extra with USER_WALLET_PRICE key. Check what type response.user.wallet.credit is, int? long? serializable? and make sure you get it by the same type

try this, it may help

    Intent intent = new Intent(getActivity(), LoadActivity.class);
    intent.putExtra(USER_WALLET_PRICE, response.user.wallet.credit)
    intent.putExtra(USER_CHARGED_VALUE, 0)
    startActivity(intent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM