I am trying to pass two strings from AddNote to MainActivity. But it keeps getting null.
Unable to start activity (MainActivity)
java.lang.IllegalStateException: callingIntent.getStringExtra("intentTitle") must not be null
class MainActivity : AppCompatActivity() {
private val notes = arrayListOf<Note>()
private val db by lazy {
Room.databaseBuilder(this
,NoteDatabase::class.java
,"NoteDatabase.db")
.allowMainThreadQueries()
.build() }
lateinit var adapter: adapter
lateinit var title: String
lateinit var content: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
notes.addAll(db.dao().getNotes())
AddNote.setOnClickListener {
val i = Intent(this#MainActivity,AddNote::class.java)
startActivity(i)
}
// startActivity(Intent(this, AddNote::class.java))
val callingIntent = intent
title = callingIntent.getStringExtra("intentTitle")
content = callingIntent.getStringExtra("intentContent")
val note = Note(title,content)
val id = db.dao().insert(note)
note.id = id.toInt()
notes.add(note)
adapter = adapter(notes, db)
rootView.layoutManager = LinearLayoutManager(this)
rootView.adapter = adapter
}
override fun onResume() {
super.onResume()
notes.clear()
notes.addAll(db.dao().getNotes())
adapter.notifyDataSetChanged()
}
}
class AddNote : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_note)
var intentTitle = "Title"
var intentContent = "Content"
saveNote.setOnClickListener {
intentTitle = addTitle.text.toString()
intentContent = addContent.text.toString()
}
val i = Intent()
i.putExtra("title",intentTitle)
i.putExtra("content",intentContent)
startActivity(i)
}
}
You must start activity like this...
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)
You must put the code that starts MainActivity inside saveNote.setOnClickListener:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_note)
var intentTitle = "Title"
var intentContent = "Content"
saveNote.setOnClickListener {
intentTitle = addTitle.text.toString()
intentContent = addContent.text.toString()
val i = Intent(this, MainActivity::class.java)
i.putExtra("title",intentTitle)
i.putExtra("content",intentContent)
startActivity(i)
}
}
The way your code worked was to start MainActivity as soon as AddNote activity was loaded, so I'm not sure what you are trying to do.
Related
I had one learning project that require RecyclerView item to send his detailed data to another activity with getParcelableExtra, my problem is when I clicked the item, the data is null on detailsActivity then I check it with the log.d, and yes it's null. any solution ;
here's the code main activity
class MainMyRecyclerViewActivity : AppCompatActivity() {
private lateinit var binding: ActivityMyrecyclerviewMainBinding
private lateinit var rvHeroes: RecyclerView
private val list = ArrayList<Hero>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMyrecyclerviewMainBinding.inflate(layoutInflater)
setContentView(binding.root)
rvHeroes = binding.rvMymainRv
rvHeroes.setHasFixedSize(true)
list.addAll(listHeroes)
showRecyclerList()
}
private fun showRecyclerList() {
//on change orientation adapter behavior
if (applicationContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
rvHeroes.layoutManager = GridLayoutManager(this, 2)
} else {
rvHeroes.layoutManager = LinearLayoutManager(this)
}
val listHeroAdapter = ListHeroAdapter(list)
rvHeroes.adapter = listHeroAdapter
listHeroAdapter.setOnItemClickCallBack(object : OnItemClickCallback {
override fun onItemClicked(data: Hero) {
showSelectedHero(data)
sendIntent(data)
}
})
}
private fun sendIntent(dataHero: Hero) {
val intent = Intent(this#MainMyRecyclerViewActivity, DetailsActivity::class.java)
intent.putExtra("DATA", dataHero.photo)
intent.putExtra("DATA", dataHero.name)
intent.putExtra("DATA", dataHero.description)
startActivity(intent)
}
private val listHeroes: ArrayList<Hero>
get() {
val dataName = resources.getStringArray(R.array.data_name)
val description = resources.getStringArray(R.array.data_description)
val dataPhoto = resources.obtainTypedArray(R.array.data_photo)
val listHero = ArrayList<Hero>()
for (i in dataName.indices) {
val hero = Hero(dataName[i], description[i], dataPhoto.getResourceId(i, -1))
listHero.add(hero)
}
return listHero
}
private fun showSelectedHero(hero: Hero) {
Toast.makeText(this, "you selected ${hero.name}", Toast.LENGTH_SHORT).show()
}
}
here's the adapter
class ListHeroAdapter(private val listHero: ArrayList<Hero>) :
RecyclerView.Adapter<ListViewHolder>() {
private lateinit var onItemClickCallback: OnItemClickCallback
fun setOnItemClickCallBack(onItemClickCallback: OnItemClickCallback) {
this.onItemClickCallback = onItemClickCallback
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view: View =
LayoutInflater.from(parent.context).inflate(R.layout.item_myrecyclerview, parent, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val (name, description, photo) = listHero[position]
holder.imgPhoto.setImageResource(photo)
holder.tvName.text = name
holder.tvDescription.text = description
holder.itemView.setOnClickListener {
onItemClickCallback.onItemClicked(listHero[holder.adapterPosition])
}
}
override fun getItemCount(): Int = listHero.size
}
this the target activity
class DetailsActivity : AppCompatActivity() {
private lateinit var binding: ActivityDetailsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailsBinding.inflate(layoutInflater)
setContentView(binding.root)
val data = intent.getParcelableExtra<Hero>("DATA")
binding.tvDetailsNameHero.text = data?.name
binding.tvDetailsDeskription.text = data?.description
data?.photo?.let { binding.ivDetails.setImageResource(it) }
Log.d("details data", data?.name.toString())
}
}
here's is data class I've using
#kotlinx.parcelize.Parcelize
data class Hero(
var name: String,
var description: String,
var photo: Int
) : Parcelable
the interface
interface OnItemClickCallback {
fun onItemClicked(data: Hero)
}
any suggestion will be good for me, thank you.
The problem is here
intent.putExtra("DATA", dataHero.photo)
intent.putExtra("DATA", dataHero.name)
intent.putExtra("DATA", dataHero.description)
You are sending single item in your intent as a String with the same key name
The first solution would be you need to send your class object
And
the second solution should send all extra parameters with different key names
the First solution You need to pass your model class object in intent
intent.putExtra("DATA",dataHero);
instead of this
private fun sendIntent(dataHero: Hero) {
val intent = Intent(this#MainMyRecyclerViewActivity, DetailsActivity::class.java)
intent.putExtra("DATA", dataHero.photo)
intent.putExtra("DATA", dataHero.name)
intent.putExtra("DATA", dataHero.description)
startActivity(intent)
}
The Second solution send data like this with different key names
intent.putExtra("PHOTO", dataHero.photo)
intent.putExtra("NAME", dataHero.name)
intent.putExtra("DESCRIPTION", dataHero.description)
and receive data like this in your details activity
val photo = intent.getStringExtra("PHOTO");
val name = intent.getStringExtra("NAME");
val description = intent.getStringExtra("DESCRIPTION");
I think you're problem is here.
private fun sendIntent(dataHero: Hero) {
val intent = Intent(this#MainMyRecyclerViewActivity, DetailsActivity::class.java)
intent.putExtra("DATA", dataHero.photo)
intent.putExtra("DATA", dataHero.name)
intent.putExtra("DATA", dataHero.description)
startActivity(intent)
}
What you're doing here is putting the value of dataHero.photo into the Bundle with the key DATA. Then you're overwriting that with dataHero.name, and then again with dataHero.description.
You can see from the image below that there are a lot of overloaded methods that use the same name but assign a different type.
So you are able to assign almost any value to a particular key (DATA), and the reason the call to retrieve the Parcelable is null, is because the value of DATA in the end is not a Parcelable implementation. The last assignment was of type String, which does not implement the Parcelable interface.
As mentioned by #AskNilesh use
intent.putExtra("DATA", dataHero) instead.
Change sendIntent method to this:
private fun sendIntent(dataHero: Hero) {
val intent = Intent(this#MainMyRecyclerViewActivity, DetailsActivity::class.java)
intent.putExtra("DATA", dataHero)
startActivity(intent)
}
I don't know how to pass data from the dialog fragment to the Activity. I have an Activity, which creates the Dialog. From this Dialog I want to pass Data to another Activity. Anyone know I can do this?
this is my 1st Activity:
class EinkaufslisteActivity : AppCompatActivity() {
//override val kodein by kodein()
//private val factory : EinkaufsViewModelFactory by instance()
#SuppressLint("NotifyDataSetChanged")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_einkaufsliste)
val database = EinkaufDatenbank(this)
val repository = EinkaufsRepository(database)
val factory = EinkaufsViewModelFactory(repository)
val viewModel = ViewModelProviders.of(this, factory).get(EinkaufsViewModel::class.java)
val adapter = ProduktAdapter(listOf(), viewModel)
rvVorratsliste.layoutManager = LinearLayoutManager(this)
rvVorratsliste.adapter = adapter
viewModel.getAllProdukte().observe(this, Observer {
adapter.items = it
adapter.notifyDataSetChanged()
})
adapter.setOnItemClickListener {
val produkt = it
Intent(this, VorratslisteActivity::class.java).also {
it.putExtra("EXTRA_PRODUKT", produkt)
}
EinkaufslisteProduktGekauftDialog(this, produkt, object : AddDialogListener{
override fun onAddButtonClicked(produkt: Produkt) {
}
override fun onAddButtonClickedVorrat(produktVorrat: ProduktVorrat) {
viewModel.delete(produkt)
}
}).show()
}
This is my Dialog:
ass EinkaufslisteProduktGekauftDialog (context: Context, var produkt : Produkt?, var addDialogListener: AddDialogListener?) : AppCompatDialog(context){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dialog_einkaufsliste_produkt_gekauft)
tvProduktgekauftName.text = produkt?.name.toString()
etProduktGekauftAnzahl.hint = produkt?.anzahl.toString()
btnProduktGekauftOk.setOnClickListener {
val name = tvProduktgekauftName.text.toString()
val anzahl = etProduktGekauftPreis.text.toString()
val datum = etProduktGekauftDatum.text.toString()
val preis = etProduktGekauftPreis.text.toString()
if(name.isEmpty() || anzahl.isEmpty()){
Toast.makeText(context, "Bitte fülle alle Felder aus", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
val produktVorrat = ProduktVorrat(name, anzahl.toInt(), datum)
addDialogListener?.onAddButtonClickedVorrat(produktVorrat)
dismiss()
}
This is my 2nd Activity:
class VorratslisteActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vorratsliste)
val database = EinkaufDatenbank(this)
val repository = VorratsRepository(database)
val factory = VorratViewModelFactory(repository)
val viewModel = ViewModelProviders.of(this, factory).get(VorratViewModel::class.java)
val adapter = ProduktVorratAdapter(listOf(), viewModel)
rvVorratsliste.layoutManager = LinearLayoutManager(this)
rvVorratsliste.adapter = adapter
viewModel.getAllProdukteVorratsliste().observe(this, Observer {
adapter.items = it
adapter.notifyDataSetChanged()
})
val produkt = intent.getSerializableExtra("EXTRA_PRODUKT") as? ProduktVorrat
if(produkt != null) {
viewModel.upsertVorrat(produkt)
}
btnVorratNeuesProdukt.setOnClickListener {
VorratProduktHinzufuegenDialog(this,
object : AddDialogListener {
override fun onAddButtonClicked(produkt: Produkt) {
TODO("Not yet implemented")
}
override fun onAddButtonClickedVorrat(produktVorrat: ProduktVorrat) {
viewModel.upsertVorrat(produktVorrat)
}
}).show()
}
The "produkt" in activity 2 is null and i don't know why
Since you are already using a ViewModel in your code, add a LiveData variable in your view model and set that live data on the Dialog.
To get the value of the live data from another activity, ensure that you are using the same view model instance (using the activity view model factory). Then, you can access that view model (and live data) from that activity.
In this way, you have a single source of data that is shared between multiple ui components (activity, fragment, dialogs)
Check the official docs for Live Data here: https://developer.android.com/topic/libraries/architecture/livedata
ActivityA launches Dialog
Dialog passes result back to ActivityA
ActivityA launches ActivityB passing result from Dialog
My title is not displaying in the app.
I think there is a problem with the intent.
So, my main file is the login page and the code is:
class MainActivity : AppCompatActivity()
{
lateinit var username: EditText
lateinit var password1: EditText
lateinit var logIn: Button
lateinit var signup: TextView
lateinit var forgotpassword: TextView
val user="DiyaK"
val pass=arrayOf("Diya#2826","Sidd#2826","Prat#2826","Prash#2826")
var titlename: String? = "DiyaK"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scroll)
println("Create called")
title = "Login Page"
username=findViewById(R.id.username)
password1=findViewById(R.id.password1)
logIn=findViewById(R.id.logIn)
signup=findViewById(R.id.signup)
forgotpassword=findViewById(R.id.forgotpassword)
logIn.setOnClickListener {
val user1= username.text.toString()
val pass1=password1.text.toString()
var name="Diya K"
if(user1==user) {
if (pass1 == pass[0]) {
val intent = Intent(this#MainActivity, NewActivity::class.java)
startActivity(intent)
name="Diya K"
intent.putExtra("Name",name)
} else if (pass1 == pass[1]) {
val intent2 = Intent(this#MainActivity, NewActivity6::class.java)
startActivity(intent2)
name="Siddhant K"
intent2.putExtra("Name",name)
} else if (pass1 == pass[2]) {
val intent3 = Intent(this#MainActivity, NewActivity3::class.java)
startActivity(intent3)
name="Pratibha K"
intent3.putExtra("Name",name)
} else if (pass1 == pass[3]) {
val intent4 = Intent(this#MainActivity, NewActivity4::class.java)
startActivity(intent4)
name="Prashant K"
intent4.putExtra("Name",name)
}
} else {
Toast.makeText(this#MainActivity, "Incorrect! Try again", Toast.LENGTH_SHORT)
.show()
}
}
}
}
And, I have created 4 new activities, like for each different page and the code for all are similar, so I am showing the code for one only.
class NewActivity : AppCompatActivity() {
lateinit var img: ImageView
lateinit var state: TextView
lateinit var btn: Button
lateinit var btn1: Button
lateinit var header: TextView
lateinit var subheader: TextView
lateinit var hobby: TextView
var title1: String? = "Diya K"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new1)
img = findViewById(R.id.img)
state = findViewById(R.id.state)
btn = findViewById(R.id.btn)
btn1 = findViewById(R.id.btn1)
header = findViewById(R.id.header)
subheader = findViewById(R.id.subheader)
hobby=findViewById(R.id.hobby)
btn1.setOnClickListener {
Toast.makeText(this#NewActivity, "Hurray", Toast.LENGTH_SHORT).show()
val intent1 = Intent(this#NewActivity, MainActivity::class.java)
startActivity(intent1)
}
if(intent != null) {
title1=intent.getStringExtra("Name")
}
title=title1
}
}
My title is not displaying in the app. I think there is a problem with the intent.
The problem is you are setting the title after starting the activity
startActivity(intent)
name="Diya K"
intent.putExtra("Name",name)
Solution is set the extras first before starting the activity. Just swap the lines like below:
name="Diya K"
intent.putExtra("Name",name)
startActivity(intent)
if(intent != null) {
title1=intent.getStringExtra("Name")
}
title=title1
header.setText(title)// you get value but not set
I am trying to send input from the user to the second screen. The values are dgc, outMEA, and so on. Below is the code of the main activity, with a button that sends you to the second screen:
package com.example.prodapp12
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.sulfur
class MainActivity : AppCompatActivity() {
companion object {
const val dgc = "dgc" // key for Your value, You have to define each key for every value that You want to pass to another activity
const val dcx = "dcx"
const val outmea = "outmea"
const val outdea = "outdea"
const val sulfur = "sulfur"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dgc = dgc
val dcx = dcx
val outmea = outmea
val outdea = outdea
val sulfur = sulfur
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rezultate)
val dcx = intent.getStringExtra(MainActivity.dcx) // receive saved value
Log.d("dcx", "Your value: dcx") // D/MyTag: Your value: My string
val dgc = intent.getStringExtra(MainActivity.dgc)
Log.d("dgc", "Your value: dgc")
val outmea = intent.getStringExtra(MainActivity.outmea)
Log.d("outmea", "Your value: outmea")
val outdea = intent.getStringExtra(MainActivity.outdea)
Log.d("outdea", "Your value: outdea")
val sulfur = intent.getStringExtra(MainActivity.sulfur)
Log.d("sulfur", "Your value: sulfur")
}
}
calc.setOnClickListener {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra("dcx", "dcx") // add value to intent with defined key
putExtra("dgc", "dgc") // add value to intent with defined key
putExtra("outmea", "outmea") // add value to intent with defined key
putExtra("outdea", "outdea") // add value to intent with defined key
putExtra("sulfur", "sulfur") // add value to intent with defined key
}
startActivity(Intent(this, Rezultate::class.java))
}
}
}
The inMEA is a textView that needs to display some simple arithmetic calculation using the input values from the first screen
And this is the second screen:
package com.example.prodapp12
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_rezultate.*
class Rezultate : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rezultate)
val extras = intent.extras
if (extras != null) {
val dcx = extras.getString("dcx")
val dgc = extras.getString("dgc")
val outmea = extras.getString("outmea")
val outdea = extras.getString("outdea")
val sulfur = extras.getString("sulfur")
//The key argument here must match that used in the other activity
}
Ref.setOnClickListener {
inMEA.text = intent.getStringExtra(MainActivity.sulfur)
}
}
}
Here is example how You can do it:
MainActivity:
class MainActivity : AppCompatActivity() {
companion object {
const val YOUR_VALUE_KEY = "YOUR_VALUE_KEY" // key for Your value, You have to define each key for every value that You want to pass to another activity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val yourValue = "My string"
// create listenner for button
buttonGoToResultActivity.setOnClickListener {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra(YOUR_VALUE_KEY, yourValue) // add value to intent with defined key
}
startActivity(intent) // start activity
}
}
}
ResultActivity:
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
val receivedYourValue = intent.getStringExtra(MainActivity.YOUR_VALUE_KEY) // receive saved value
Log.d("MyTag", "Your value: $receivedYourValue") // D/MyTag: Your value: My string
}
}
MainActivity:
class MainActivity : AppCompatActivity() {
companion object {
const val DGC_KEY = "DGC_KEY"
const val DCX_KEY = "DCX_KEY"
const val OUTMEA_KEY = "OUTMEA_KEY"
const val OUTDEA_KEY = "OUTDEA_KEY"
const val SULFUR_KEY = "SULFUR_KEY"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dgc = "dgc_value"
val dcx = "dcx_value"
val outmea = "outmea_value"
val outdea = "outdea_value"
val sulfur = "sulfur_value"
calc.setOnClickListener {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra(DGC_KEY, dgc)
putExtra(DCX_KEY, dcx)
putExtra(OUTMEA_KEY, outmea)
putExtra(OUTDEA_KEY, outdea)
putExtra(SULFUR_KEY, sulfur)
}
startActivity(intent)
}
}
}
ResultActivity:
class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
val dgc = intent.getStringExtra(MainActivity.DGC_KEY)
val dcx = intent.getStringExtra(MainActivity.DCX_KEY)
val outmea = intent.getStringExtra(MainActivity.OUTMEA_KEY)
val outdea = intent.getStringExtra(MainActivity.OUTDEA_KEY)
val sulfur = intent.getStringExtra(MainActivity.SULFUR_KEY)
Log.d("MyTag", "dgc = $dgc")
Log.d("MyTag", "dcx = $dcx")
Log.d("MyTag", "outmea = $outmea")
Log.d("MyTag", "outdea = $outdea")
Log.d("MyTag", "sulfur = $sulfur")
}
}
Logs:
D/MyTag: dgc = dgc_value
D/MyTag: dcx = dcx_value
D/MyTag: outmea = outmea_value
D/MyTag: outdea = outdea_value
D/MyTag: sulfur = sulfur_value
There is a more reusable approach.
class ResultsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val param1 = intent.getStringExtra(PARAM1)
val param2 = intent.getStringExtra(PARAM2)
val param3 = intent.getIntExtra(PARAM3,0)
Log.d("PARAMS::","$param1,$param2,$param3")
}
companion object {
private const val PARAM1 = "param_1"
private const val PARAM2 = "param_2"
private const val PARAM3 = "param_3"
fun start(context: Context, param1: String, param2: String, param3:Int){
val intent = Intent(context, ResultsActivity::class.java).apply {
putExtra(PARAM1, param1)
putExtra(PARAM2, param2)
putExtra(PARAM3, param3)
}
context.startActivity(intent)
}
}}
Then in the main activity,
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
someButton.setOnClickListener {
//You can just call this in any other place you may want to open the ResultsActivity
ResultsActivity.start(this, "Hello", "World", 100)
}
}}
Results
D/PARAMS:: Hello,World,100
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button1: Button = findViewById(R.id.button1)
val editText1: EditText = findViewById(R.id.editText1)
val editText2: EditText = findViewById(R.id.editText2)
val firstNumber = editText1.toString().toInt()
val secondNumber = editText2.toString().toInt()
val product = firstNumber * secondNumber
button1.setOnClickListener{
val intent = Intent(this, Activity2::class.java)
intent.putExtra("RESULT_PRODUCT", product)
startActivity(intent)
}
}
}
Here is my code for Activity2:
class Activity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_2)
val product = intent.getIntExtra("RESULT_SUM", 0)
textView1.text = product.toString()
}
}
I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.
First of all, You have to calculate the product inside OnClickListener to get correct result.
button1.setOnClickListener{
val firstNumber = editText1.text.toString().trim()
val secondNumber = editText2.text.toString().trim()
if(!(firstNumber.isEmpty() or secondNumber.isEmpty())) {
val product = firstNumber.toInt() * secondNumber.toInt()
val intent = Intent(this, Activity2::class.java)
intent.putExtra("RESULT_PRODUCT", product)
startActivity(intent)
} else {
//Show messages
}
}
And then you have to use the exact key RESULT_PRODUCT that you use in your activity to pass data through intent
val product = intent.getIntExtra("RESULT_PRODUCT", 0)
You are passing "RESULT_PRODUCT" from MainActivity but getting "RESULT_SUM" in your Activity2. You should use intent.getIntExtra("RESULT_PRODUCT", 0) in you second activity.