String Reversal Program, Kotlin - android

I've recently decided to start learning Kotlin, and I've started a mini project to create a program that outputs a user inputted string, but in reverse.
I've built a version that uses Typed Array to store a user given string, then reverses each word within that array before returning the string but in reverse. Currently it doesn't work as intended, when the program is run, it doesn't crash and I have no error logs, but the program output looks like: [Ljava.lang.string;#2d112c3. The output I'd be expecting would be, for example: user given string: Hello World, program output: olleH dlroW. I've had a look around online and seen a few other programs of a similar nature but I so far, have been unable to fix the issues in my version.
acitivty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/useButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="158dp"
android:layout_marginEnd="159dp"
android:layout_marginBottom="275dp"
android:text="Reverse String"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/userInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="100dp"
android:layout_marginTop="240dp"
android:layout_marginEnd="101dp"
android:ems="10"
android:hint="Enter a Word or String"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/programOutput"
android:layout_width="210dp"
android:layout_height="42dp"
android:layout_marginStart="100dp"
android:layout_marginTop="41dp"
android:layout_marginEnd="101dp"
android:layout_marginBottom="40dp"
android:text=""
app:layout_constraintBottom_toTopOf="#+id/useButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/userInput" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
#file:Suppress("UNUSED_CHANGED_VALUE")
package com.example.stringreversal
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val userString = findViewById<EditText>(R.id.userInput)
val submitButton = findViewById<Button>(R.id.useButton)
val changeText = findViewById<TextView>(R.id.programOutput)
submitButton.setOnClickListener {
val getString = userString.text
val typedArray: Array<String> = getString.split(" ").toTypedArray()
val count = typedArray.count()
var nul: Int = 0
while (nul <= count) {
for (word in typedArray) {
word.reversed()
}
nul++ }
val reverseString = typedArray.toString()
changeText.text = reverseString
}
}
}

I think you should use typedArray.joinToString(" ") instead of typedArray.toString()

change
val getString = userString.text
to
val getString = userString.text.toString()
userString.text returns an object of Editable type. To get string value from EditText you have call toString() from Editable object.

Related

Android with Kotlin - Sending data back to MainActivity

I have two activities. I want to receive a value from MainActivity, change the value from SecondActivity, and send it back to editText of MainActivity.
However, the editText of MainActivity does not change even if I move back from SecondActivity.
Could you tell me which part I misunderstood?
MainActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.homework07.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.resultCode
val ret_num = it.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
binding.button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("num", Integer.parseInt(binding.editText.text.toString()))
result.launch(intent)
}
}
}
activity_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Enter number only"
android:inputType="number"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="START SECOND ACTIVITY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
SecondActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.example.homework07.databinding.ActivitySecondBinding
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySecondBinding.inflate(layoutInflater)
setContentView(binding.root)
val viewModel = ViewModelProvider(this)[MyViewModel::class.java]
viewModel.myLiveData.observe(this) {
binding.textView.text = "$it"
}
var num2 = intent?.getIntExtra("num", 0) ?:0
binding.textView.text = "$num2"
binding.buttonInc.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) + 1
}
binding.buttonDec.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) - 1
}
setResult(0, Intent().putExtra("result", num2))
}
}
activity_second.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonInc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="INCREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonDec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="DECREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toBottomOf="#+id/buttonInc" />
</androidx.constraintlayout.widget.ConstraintLayout>
MyViewModel.kt code
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MyViewModel : ViewModel() {
val myLiveData : MutableLiveData<Int> = MutableLiveData()
}
Thank you.
You made a mistake:
setResult(0, Intent().putExtra("result", num2))
replace 0 (it cancel result) to Activity.RESULT_OK.
This line has a mistake (resultCode) parameter:
setResult(0, Intent().putExtra("result", num2))
It's better if you make a constant for resultCode or do something like this in your SecondActivity.kt.
setResult(200, Intent().putExtra("result", num2))
And in MainActivity.kt add this is "registerActivityForResult":
if(it.resultCode == 200){
//Rest of the code here
}
Or you can also follow Below answer
You should set the result before finishing the SecondActivity with:
intent.putExtra("result", num2)
setResult(Activity.RESULT_OK, intent)
finish()
The, after checking the result, retrieve the value in the FirstActivity:
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val ret_num = result.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
}

Changing text value with Kotlin in Android Studio

New to Kotlin, I've followed the guide on how to set up a basic "Press the button and it changes text" However Whenever I press the button, the app crashes and in the debugger I get
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)'
on a null object reference at com.example.myapplication.MainActivity.One(MainActivity.kt:16)
Here is my current MainActivity.KT:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun One(view: android.view.View) {
val onetext = view.findViewById<TextView>(R.id.textView)
onetext.text = "Hello"
}
}
And my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="168dp"
android:layout_height="90dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="One"
android:text="Button"
tools:layout_editor_absoluteX="163dp"
tools:layout_editor_absoluteY="462dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you!
The problem is onetext is null, which means view.findViewById<TextView>(R.id.textView) didn't find a view with textView as id inside of view. The view passed in the function is the button, which has no textView as a child. You need to search for the textView in a view higher in the hierarchy.
In the specific example, one way of doing that is by omitting the view receiver, like so:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun One(view: android.view.View) {
val onetext = findViewById<TextView>(R.id.textView)
onetext.text = "Hello"
}
}
This way it will search for the textView id in the Activity's view, which is the activity_main layout.
I believe the problem has already been solved, but I noticed that in the xml file the button is not properly docked, putting:
app:layout_constraintTop_toBottomOf="#id/textView"
the button would be below the TextView component and putting:
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
the button would be centered on the screen...
Button code would look like this
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="One"
android:text="Button"
app:layout_constraintTop_toBottomOf="#id/textView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>

How to replace documentPath by a string that can be changed by a user in Android Studio Kotlin?

I am trying to build a little app where the user can find values of documents.
As a database I am using Firestore Database. I only have one collection "storage" with many documents and 3 value fields per document. I already built an activity that gets the 3 value fields from the database (see below).
What I am trying to do now is to let the user decide which values he wants to see by selecting different database document names.
For example if the user types in "apple" in a text input field, I want to show him the 3 values that I have saved in the collection "storage" -> document "apple" -> fields "value1", "value2" and "value3". If the user types in "banana" in the text input field, I want to show him the 3 values that I have saved in the collection "storage" -> document "banana" -> fields "value1", "value2" and "value3".
Could anyone give me a few tips how to implement that? Unfortunately I couldnt find much help elsewhere.
MainActivity.kt
package com.example.test
import android.content.ContentValues.TAG
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Firebase.firestore
val value1= findViewById(R.id.value1) as TextView
val value2= findViewById(R.id.value2) as TextView
val value3= findViewById(R.id.value3) as TextView
val docRef = db.collection("storage").document("apple")
docRef.get()
.addOnSuccessListener { document ->
if (document !=null) {
Log.d("exist", "DocumentSnapshot data: ${document.data}")
value1.text = document.getString("value1")
value2.text = document.getString("value2")
value3.text = document.getString("value3")
} else {
Log.d("noexist", "No such docoument")
}
}
.addOnFailureListener { exception ->
Log.w("notexisting", "Error getting documents.", exception)
}
}
}
activity_main.xml (looks horrible, but for now I just wanna work out the functionality)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.585" />
<TextView
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.873"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.585" />
<TextView
android:id="#+id/value3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.162"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.586" />
</androidx.constraintlayout.widget.ConstraintLayout>
You'll need to introduce a new field where the user can enter or select the document name. Once you have that, you can read its value and use that when accessing the database with something like this:
...
val value1= findViewById(R.id.value1) as TextView
val value2= findViewById(R.id.value2) as TextView
val value3= findViewById(R.id.value3) as TextView
val documentId = (findViewById(R.id.documentId) as TextView).getText().toString()
// 👆 Get the value the user entered here
val docRef = db.collection("storage").document(documentId)
// 👆 Then use it here
docRef.get()
.addOnSuccessListener { document ->
...

Why is my Android Studio (Kotlin) showing the layout of an Android phone in Preview but not in the Build App?

I made a simple app in the Android Studio. I took two TextViews and one Button in XML layout file. Both textview and Button are showing in the preview but in the Build Apk there is only Button Showing. It doesn't giving any error. I don't know what is the problem I tried all the possible ways to fix it but didn't get anything.
activity_home XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="mnail"
android:id="#+id/editText"/>
<EditText
android:id="#+id/textViewSendEmail"
android:layout_width="344dp"
android:layout_height="44dp"
android:hint="Email"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"/>
<EditText
android:id="#+id/textViewSendPassword"
android:layout_width="344dp"
android:layout_height="44dp"
android:hint="Password"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_below="#+id/textViewSendEmail"/>
<Button
android:id="#+id/sendButton"
android:layout_width="344dp"
android:layout_height="44dp"
android:text="send"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_below="#+id/textViewSendPassword"/>
</LinearLayout>
MainActivity code
package com.kotlinintent
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_home.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
var email_user = textViewSendEmail.text
var password_user = textViewSendPassword.text
sendButton.setOnClickListener {
intent = Intent(this, SecondActvity::class.java)
intent.putExtra("email", email_user)
intent.putExtra("password", password_user)
startActivity(intent)
}
}
}
SecondActivity
package com.kotlinintent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_second.*
class SecondActvity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
var bundle : Bundle? = intent.extras
var emailData = bundle!!.getString("email")
var passwordData = bundle.getString("password")
textViewEmail.text = emailData
textViewPassword.text = passwordData
}
}
Second Activity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActvity">
<TextView
android:id="#+id/textViewEmail"
android:layout_width="match_parent"
android:layout_height="44dp"
android:text="Email"/>
<TextView
android:id="#+id/textViewPassword"
android:layout_width="match_parent"
android:layout_height="44dp"
android:text="Password"
android:layout_marginTop="40dp"
/>
<Button
android:id="#+id/getButton"
android:layout_width="match_parent"
android:layout_height="44dp"
android:text="get"
android:layout_marginTop="40dp"
/>
</LinearLayout>
Instead of these lines
var email_user = textViewSendEmail.text
var password_user = textViewSendPassword.text
Use this
var email_user = textViewSendEmail.text.toString()
var password_user = textViewSendPassword.text.toString()
And also you must call these lines in onclick so your code must like this
sendButton.setOnClickListener {
var email_user = textViewSendEmail.text.toString()
var password_user = textViewSendPassword.text.toString()
intent = Intent(this, SecondActvity::class.java)
intent.putExtra("email", email_user)
intent.putExtra("password", password_user)
startActivity(intent)
}
And i suggest that use wrap_content instead of static size (44dp) for height
Your issue in the way how you put extras. In MainActivity you put your data as extras for intent. But in SecondActivity you try to get data from intent's bundle.
Change this
var bundle : Bundle? = intent.extras
var emailData = bundle!!.getString("email")
var passwordData = bundle.getString("password")
for this
var emailData = intent.getStringExtra("email")
var passwordData = intent.getStringExtra("password")`
Or you can put data into Bundle in MainActivity, then put this Bundle into intent. And then get data, as you do with your current solution.

android kotlin - app keep keeps stopping when i click the button

I start doing a simple android app for practice to calculate the age with Kotlin programming language, when i click the button the app, can someone help me with this and fix it to know where is my wrong because I am just very beginner
package com.calcult.age.agecalcult
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var ageInput = ageText.text.toString()
doIT.setOnClickListener{
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = currentYear-ageInput.toInt()
Toast.makeText(this, getAge, Toast.LENGTH_LONG)
}
}
}
XML FILE :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="148dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="148dp"
android:id="#+id/doIT"
android:text="#string/button_text1"
android:textSize="18sp"
app:layout_constraintHorizontal_bias="0.0" android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent" android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="0.771"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/ageText" app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="215dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="85dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="84dp"
android:layout_marginBottom="250dp" app:layout_constraintBottom_toTopOf="#+id/doIT"/>
</android.support.constraint.ConstraintLayout>
As Vladyslav Matviienko said you're trying to get the text onCreate, what you need to do is something like this:
//Here the view is already created, so you'll be able to setup everything you need.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupListener()
}
//If you are learning, you should consider reading a bit about clean code,
//it's always nice that a function does just one job, that's why I broke the code
//below in two little functions. Have in mind, this code is not the best, but at the
//moment i don't have much time to write this.
private fun setupListener() {
doIT.setOnClickListener{
//Always be aware of the type of the variables, when i wrote the first answer i was
//trying to do a math operatiton using a string, so it would not work. =P
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = (currentYear-getAge().toInt()).toString()
Toast.makeText(this, getAge, Toast.LENGTH_LONG).show()
}
}
private fun getAge(): String {
return ageText.text.toString
}

Categories

Resources