Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – when The function is called the app crashes

Posted on November 11, 2022 By

Solution 1 :

You should not use textField.toString() to get the value of an EditText, use textField.text.toString(). Calling textField.toString() will produce something that looks like this:

androidx.appcompat.widget.AppCompatEditText{adc99c5 VFED..CL. ......I. 0,0-0,0 #7f080062 app:id/cost_of_service}

You should also guard against blank or non-integer entries, like this:

val txtStr = textField.text.toString()
val txtVal =  txtStr.toIntOrNull() ?: 0 // if it cannot be converted to an int, use 0
val price = txtVal * 0.2

When you use Integer.parseInt(str) or str.toInt() it will throw a NumberFormatException if str is blank or a non-integer. If you use toIntOrNull() it will return null in that case, and then the ?: 0 will assign the output to 0 instead of crashing. You could also choose to catch that case and show an error message instead, like this

val txtStr = textField.text.toString()
val txtVal =  txtStr.toIntOrNull()

if( txtVal == null ) {
    println("ERROR: could not convert $txtStr to an integer")
    // show a toast error or something
    return
}

// then you can safely use txtVal

If your price entry could be a floating point number (e.g. “12.56”) you should use toFloatOrNull() (or toDoubleOrNull()) instead of toIntOrNull().

Also, when your app crashes you can look in the Logcat tab to find the error message and stack trace. You should look there first to see what the problem is, and if you still have a question always include that in your question.

Problem :

I am working on an application that calculate Tips.

To calculate The tip I created 3 Radio Buttons, and The tip will be calculated according to the selected Option.
and I have Edit Text to take the price of the service from the user, and The result is Supposed to appear in The same edit text.

READ  [FIXED] Attempt to invoke virtual method 'android.content.ContentResolverr android.id.content.Context.getContentesolver()' on a nul object reference
Powered by Inline Related Posts

I created This method in The main activity:

private fun calculate()
{
    val tipButtons : RadioGroup = findViewById(R.id.tip_options)
    val textField : EditText = findViewById(R.id.cost_of_service)

    when (tipButtons.checkedRadioButtonId) {
        R.id.amazing -> {

            val price =   Integer.parseInt(textField.toString())*0.20
          textField.setText(""+price)

        }
        R.id.good -> {
            println("good!")
            println(textField.toString())
            val price =   Integer.parseInt(textField.toString())*0.18
            textField.setText(""+price)
        }
        R.id.okay -> {
            println("okay!")
            println(textField.toString())
            val price =   Integer.parseInt(textField.toString())*0.15
            textField.setText(""+price)
        }
    }


}

—-Main Activity—

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val myButton: Button = findViewById(R.id.button)
    myButton.setOnClickListener{
        calculate()
    }
}

Edit text xml code:

<EditText
        android_id="@+id/cost_of_service"
        android_layout_height="wrap_content"
        android_layout_width="160dp"
        app_layout_constraintStart_toStartOf="parent"
        app_layout_constraintTop_toTopOf="parent"
        android_inputType="numberDecimal"
        android_hint="@string/cost_of_service"/>

But when I enter a value and click The Button The app Craches.

Android Tags:android, kotlin

Post navigation

Previous Post: [FIXED] android – How to detect when third party app’s dialog box appears in React native?
Next Post: [FIXED] android – Get the list of user SIM cards and select it – flutter

Related Posts

[FIXED] android – Not receiving OTP from Firebase Android
[FIXED] android – ImageSpan on pre lolipop returns null Android
[FIXED] How can I securely store data on Android that will survive a reinstall? Android
[FIXED] android camerax – OutputFileResults returned by OnImageSavedCallback has an invalid Uri Android
[FIXED] java – NFC is on, but adapter is not enabled Android
[FIXED] java – Replace “,” with “. ” in TextWatcher Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What are the main features of Islamic education?
  • Is the Jeep 4xe worth it?
  • How does the ringer work on cast iron?
  • What is the biggest size interior door?
  • Is blue raspberry an original Jolly Rancher flavor?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme