0

I want to reveive value that i passed throught Intent from activity to another and access it, but it's showing:

Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

So here what i did... in the Login Activity I passed username thourgh Intent:

val intent = Intent(this@LoginActivity,MainActivity::class.java)
intent.putExtra("username", "johnDoe")
startActivity(intent)

Main Activity

class MainActivity : AppCompatActivity() {

    val username = intent.getStringExtra("username")

    private val firebaseHelper = FirebaseHelper(username)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Toast.makeText(applicationContext, username.toString(), Toast.LENGTH_LONG).show()
    }

    override fun onStop() {
        super.onStop()
        firebaseHelper.deleteDriver()
    }
}

Fore example: if i use val username = intent.getStringExtra("username") it will work, but then i will get problem with firebaseHelper.deleteDriver().

i don't know where i missed it, but hope there's solution you can make guys

Lafoune
  • 436
  • 2
  • 12
  • 28
  • and how is that suppose to help, that nothing to do with my question @Hypino – Lafoune Sep 13 '19 at 14:51
  • I dont know Kotlin. However in MainActivity where was intent declared? As for your question, you are probably using an intent you haven´t recieved yet. I think Android sends it onNewIntent(); I dont think you can set Activity based variables in the get go. For example, I did... java.io.File appDir = Activity.this.getFilesDir(); My app kept crashing! What I had to do was initialize this variable in onCreate(); –  Sep 13 '19 at 15:26

2 Answers2

0

You should call this code val username = intent.getStringExtra("username") in the onCreate method.

Agnaramon
  • 851
  • 10
  • 15
  • but i want to use `username` in `onStop` too – Lafoune Sep 13 '19 at 15:13
  • declare them globally in your ```MainActivity``` class -> ```lateinit var firebaseHelper = FirebaseHelper``` and ```lateinit var username: String```. Then you can create your ```FirebaseHelper``` instance in ```onCreate``` method – Agnaramon Sep 13 '19 at 15:40
0

initailize

val username = intent.getStringExtra("username")

inside oncreate()

In onstop when firebaseHelper.deleteDriver() executes, it get username as null. So it is throwing NPE

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kishan Maurya
  • 3,356
  • 8
  • 21
  • what about if i have other funtions accessing `username` what should i do, since it only works at `onCreate` – Lafoune Sep 13 '19 at 15:16