Zane
Zane

Reputation: 33

Trying to read a number from a text view in kotlin for android, all usual methods crash the app

I'm trying to read a decimal number from a text view in Kotlin on Android Studio. Here is my code:

var time1 = findViewById<TextView>(R.id.time1)
var time1String: String = time1.toString()
var time1Float: Float = time1String.toFloat()
//var Time1Double = java.lang.Double.parseDouble(time1String)
//time1Float = time1Float * 1000
//var time1Long: Long = time1Double.toLong()

Commenting Line 3 makes the code run correctly. Uncommenting any of the commented lines results in the app compiling, loading to the android VM, then crashing as soon as the app runs. As long as they are commented it runs fine, but without the intended functionality.

the error that results when the code is ran as shown above:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 1067
java.lang.NumberFormatException: For input string: "android.support.v7.widget.AppCompatEditText{cf45b9b VFED..CL. .F...... 42,263-592,381 #7f070089 app:id/time1}"
    at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
    at java.lang.Double.parseDouble(Double.java:547)
    at com.example.myapplication.MainActivity$onCreate$9.onClick(MainActivity.kt:149)
    at android.view.View.performClick(View.java:5610)
    at android.view.View$PerformClick.run(View.java:22265)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Application terminated.

Thank you all for the Help!

Upvotes: 3

Views: 1308

Answers (2)

Ben P.
Ben P.

Reputation: 54204

Let's talk about this code:

var time1 = findViewById<TextView>(R.id.time1)
var time1String: String = time1.toString()

The first line will assign a TextView to your time1 variable, which is great. The second line, though, is not going to access the text being displayed in that view, but will instead convert the TextView itself to a String. You can see from the logs that this is giving you this value:

"android.support.v7.widget.AppCompatEditText{cf45b9b VFED..CL. .F...... 42,263-592,381 #7f070089 app:id/time1}"

To get the text "inside" the TextView, write this instead:

var time1String = time1.text.toString()

Once you have that in place, you should be able to parse the text as normal.

Upvotes: 4

Jamil
Jamil

Reputation: 1820

Without being able to run the code, I think you need to parse the text you get from the time1 variable. time1 is a TextView, you’re trying to parse the Textview to a string. You will need time1.text

Upvotes: 0

Related Questions