URL在Kotlin中的正确用法是什么?

时间:2019-08-15 14:31:28

标签: android android-studio kotlin

我正在学习在Android Studio中使用Kotlin进行编码,并希望创建一个简单的应用程序来显示温度。但是应用程序不断失败,我不知道问题出在哪里。有人可以帮我吗?

该应用程序适用于Android(当然,我使用的是Android Studio)。我知道将其写入应用程序本身的代码没有失败,但是从网站读取的部分却失败了。该网站本身是一个黑色网站,其中包含4个字符,显示温度(例如21.0)。

我的代码是这样:

val knop = findViewById<Button>(R.id.button)
val temperatuur = findViewById<TextView>(R.id.temperatuur)

knop.setOnClickListener {
    var temp = URL("http://192.168.1.195/temp.txt").readText(Charset.forName("ISO-8859-1"))
        //val temp = "21.0"
        temperatuur.text = ("The temperature is $temp °C")
    }

还有更多代码,但这只是正常的自动代码。问题出在“ var temp = URL”行中

我希望输出为网站上的数字(例如21.0),但应用程序崩溃了。它给了我这个错误信息:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.raspberrypi, PID: 4972
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
 Caused by: java.net.SocketException: Permission denied
    at java.net.Socket.createImpl(Socket.java:454)
    at java.net.Socket.getImpl(Socket.java:517)
    at java.net.Socket.setSoTimeout(Socket.java:1108)
    at com.android.okhttp.Connection.connectSocket(Connection.java:195)
    at com.android.okhttp.Connection.connect(Connection.java:172)
    at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
    at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
    at java.net.URL.openStream(URL.java:1057)
    at kotlin.io.TextStreamsKt.readBytes(ReadWrite.kt:150)
    at com.example.raspberrypi.MainActivity$onCreate$1.onClick(MainActivity.kt:20)
    at android.view.View.performClick(View.java:5612)
    at android.view.View$PerformClick.run(View.java:22285)
    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:6123)
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

0 个答案:

没有答案