1

I want to simply start an activity and send some data to my second activity , this is my code :

Activiy main:

 val intent = Intent(this@MainActivity, Cards::class.java)
            intent.putExtra("title", catItem.name)
            intent.putExtra("catId", catItem.id)
            startActivity(intent)

catItem is not null and every item in it has value , i've debugged and I'm sure about it .

the second activity that I need to get data :

 val bl:Bundle=intent.extras
    catId=bl.getString("catId")
    title=bl.getString("title")

it crashes on the second line :

 bl.getString("catId") must not be null

I debugged and the bundle is completely empty .

what is wrong with this code ?

Navid Abutorab
  • 1,667
  • 7
  • 31
  • 58
  • Because you are passing data into Intent but getting its using Bundle. There is no need to get data using bundle. Just call intent.getStringExtra("catId") if catId is string. – Nick Bapu May 06 '19 at 08:37
  • 1
    Possible duplicate of [How to pass the values from activity to another activity in kotlin](https://stackoverflow.com/questions/45157567/how-to-pass-the-values-from-activity-to-another-activity-in-kotlin) – Nikunj Paradva May 06 '19 at 08:47

4 Answers4

3

To retrieve data on second activity you just need to access directly intent's extra data as follows:

val catId = intent.getStringExtra("catId")

Also, be sure that "catId" type is String (an ID usually is an Integer or Long), because if it is not an String, you will get the same error.

AlexTa
  • 5,133
  • 3
  • 29
  • 46
2

According to your activity start code(just copy of your code):

val intent = Intent(this@MainActivity, Cards::class.java)
            intent.putExtra("title", catItem.name)
            intent.putExtra("catId", catItem.id)
            startActivity(intent)

In Cards Activity onCreate method:

if they are

Required:

val arguments = requireNotNull(intent?.extras){"There should be parameters or your more meaningful message."} 

with(arguments){
          catId = getString("catId")
          title = getString("title")
         }

Not Required:

catId = intent?.extras?.getString("catId").orEmpty()
title= intent?.extras?.getString("title").orEmpty()

or

catId = intent?.extras?.getString("catId","default Cat").orEmpty()
title= intent?.extras?.getString("title","default Title").orEmpty()
ibrahimyilmaz
  • 18,331
  • 13
  • 61
  • 80
0

Change getExtra to getStringExtra

bl.getStringExtra("catId")
elbert rivas
  • 1,464
  • 1
  • 17
  • 15
0

I think in your code catItem.id is null, because of it catId is null, which causes of crash.

Please try below code to overcome the crash:

var bundle :Bundle ?=intent.extras
var title = bundle!!.getString("title")
var catId = bundle!!.getString("catId")

I hope its work for you.

Android Geek
  • 8,956
  • 2
  • 21
  • 35