This is the main activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var userInput:EditText = findViewById(R.id.usr_input) as EditText
var button:Button = findViewById(R.id.ent_btn) as Button
button.setOnClickListener {
var name = userInput.text
val intent = Intent(this#MainActivity, screenTwo::class.java)
intent.putExtra("name", name)
startActivity(intent)
}
}
}
This is second screen
class screenTwo : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_screen_two)
var userName:TextView = findViewById(R.id.user_name) as TextView
var editText:EditText = findViewById(R.id.usr_text) as EditText
var outText:TextView = findViewById(R.id.output) as TextView
var showButton:Button = findViewById(R.id.btn_show) as Button
var back:Button = findViewById(R.id.btn_back) as Button
var name = intent.getStringExtra("name")
userName.text = name
showButton.setOnClickListener {
var text:String = editText.text.toString()
outText.text = text
}
back.setOnClickListener {
var goback = Intent(this#screenTwo, MainActivity::class.java)
startActivity(goback)
}
}
}
When I click on the button(variable_name) in the main activity, the app closes. Is it the intent or something is wrong in the second screen???
intent is not defind in SecondActivity
In SecondActivity : get intent by getIntent()
class screenTwo : AppCompatActivity() {
var name = getIntent().getStringExtra("name")
Most common error in this configuration is that you forgot to declare your screenTwo in your AndroidManifest.xml, inside the "application" node (your MainActivity should already be defined there) :
<activity
android:name=".screenTwo"
android:theme="yourTheme"/>
If this is not it, an error log might help us help you.
Sorry , it was a minor error from my side..
I didn't convert the variable 'name' to 'String'
var name = userInput.text.toString() //correction
It's working now,
Thanks anyway...
Related
I'm new at Kotlin, and I'm doing a simple app where the user writes something on EditText, presses a button then the app proceeds to show that text on SecondActivity, on that SecondActivity the user can do exactly the same thing, but on the FirstActivity (the one who shows up on the user starts the app) there are on EditText with "Welcome" text for default that shows empty when the application starts, this started to happen when I implement the text to be substituted by what the user writes on the SecondActivity
Here's the code for the FirtActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val result = findViewById<TextView>(R.id.nomeUser)
val nameEntered = findViewById<EditText>(R.id.nameEntered)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener{
val name = nameEntered.text.toString()
val intent = Intent(this#MainActivity, NomeEscrito::class.java)
intent.putExtra("Name", name)
startActivity(intent)
}
val intent = intent
val name = intent.getStringExtra("Name")
result.text = name
}
}
And here's the code for the SecondActivity
class NomeEscrito : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nome_escrito)
val intent = intent
val name = intent.getStringExtra("Name")
val result = findViewById<TextView>(R.id.result)
result.text = name
val wordEntered = findViewById<EditText>(R.id.textPhrase)
val button2 = findViewById<Button>(R.id.button2)
button2.setOnClickListener{
val name2 = wordEntered.text.toString()
val intent2 = Intent(this#NomeEscrito, MainActivity::class.java)
intent2.putExtra("Name", name2)
startActivity(intent2)
}
}
}
The problem is in the following line of your FirstActivity:
val name = intent.getStringExtra("Name")
When you open up the app for the first time, there is no data in the intent. As a result, it returns an empty string.
You can do the a check for empty string before setting your EditText text to avoid this situation:
if (!name.isNullOrBlank()) {
result.text = name
}
Choose different keys in getStringExtra in both intent data passing
https://developer.android.com/training/basics/firstapp/starting-activity#kotlin
I am at this point on the training and have added the code as advised:
const val EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
/** Called when the user taps the Send button */
fun sendMessage(view: View) {
val editText = findViewById<EditText>(R.id.editText)
val message = editText.text.toString()
val intent = Intent(this, DisplayMessageActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, message)
}
startActivity(intent)
}
}
However it doesn't like editText in (R.id.editText). It is showing in red and pressing alt + enter has not worked on this. I am only expecting to see an error on DisplayMessageActivity.
I have tried to find a fix to this error online but I can't seem to find anything to help.
Thank you all, this has now been resolved.
User Jems asked me to check the activity_main.xml to see if I had an id of editText. I did but it had additional wording. It was showing as editTextTextName, so I amended this to show only editText and now it is happy with the code.
Try With This:
val editText = findViewById<EditText>(R.id.editText) as EditText
Update
const val EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editText = findViewById<EditText>(R.id.editText) as EditText
val message = editText.text.toString()
}
/** Called when the user taps the Send button */
fun sendMessage(view: View) {
val intent = Intent(this, DisplayMessageActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, message)
}
startActivity(intent)
}
}
In Kotlin, in loginButton.setOnClickListener function, the following codes can start ProfileActivity;
val intent=Intent(this#LoginActivity, ProfileActivity::class.java)
startActivity(intent)
finish()
From the ProfileActivity, the following codes can start TestActivity;
val intent=Intent(this#ProfileActivity, TestActivity::class.java)
startActivity(intent)
finish()
However, I want to start the TestActivity from the LoginActivity. So, I updated the codes by changing only the activity name and the codes are below:
val intent=Intent(this#LoginActivity, TestActivity::class.java)
startActivity(intent)
finish()
But, the app crashes before loading activity_test.xml. Why ?
The class in the ProfileActivity.kt is;
class profileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
}
}
The class in the TestActivity.kt is;
class TestActivity : AppCompatActivity() {
private val QUANT = false
private val LABEL_PATH = "labels.txt"
private val INPUT_SIZE = 224
#RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
var strResultUri: String? = null
strResultUri = savedInstanceState.getString(strResultUri)
} else {
setContentView(R.layout.activity_test)
textViewResult = findViewById(R.id.textViewResult)
textViewResult?.setMovementMethod(ScrollingMovementMethod())
}
}
}
var strResultUri: String? = null
strResultUri = savedInstanceState.getString(strResultUri)
What exactly you do here? Passing null inside savedInstanceState.getString() method?
Also, what do you mean by changing only the name? You mean you just changed the context in the following code?
val intent=Intent(this#LoginActivity, TestActivity::class.java)
startActivity(intent)
finish()
That code would work inside login activity for sure.
Also, is that a typing mistake. profileActivity. That's camel case (Not an accepted convention), and you call ProfileActivity::class.java. This shouldn't work. If it's just a typo, ignore it.
Most probabely your these lines cause issue:
var strResultUri: String? = null
strResultUri = savedInstanceState.getString(strResultUri)
Because you are passing strResultUri null value as parameter to getString method
It should be like this:
strResultUri = savedInstanceState.getString("yourKey")
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.
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.