【问题标题】:How can I update text of TextView in thread using kotlin如何使用 kotlin 在线程中更新 TextView 的文本
【发布时间】:2026-01-11 03:30:02
【问题描述】:

我正在从服务器接收 UDP 数据,我想将 UDP 数据显示给TextView。 但是 NullPointerException 每次都会发生。我不知道为什么。

这是我的代码:

open class MainActivity: AppCompatActivity() {

    companion object {
        lateinit var readSocket: DatagramSocket
        lateinit var readPacket: DatagramPacket
        val buffer = ByteArray(2048)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        println("Create Runnable example!")
        val threadWithRunnable = Thread(UdpDataArrival())
        threadWithRunnable.start()

        // Add text to textView1
        val textView = findViewById<TextView>(R.id.textView1)
        textView.setText("Hello World from main!\n")

        println("MainActivity onCreate success.")
    }

}

这个类是持续接收UDP数据的线程

class UdpDataArrival: Runnable, MainActivity() {

   override fun run() {
       println("${Thread.currentThread()} Runnable Thread Started.")
       readSocket = DatagramSocket(Settings.remotePort)
       readSocket.broadcast = true
       readPacket = DatagramPacket(buffer, buffer.size)
       while (true) {
           receiveUDP()
       }
   }

   open fun receiveUDP() {
       try {
            // Keep a socket open to listen to all the UDP traffic that is destined for this port
            readSocket.receive(readPacket)
            println("open fun receiveUDP packet received = " + readPacket.data)

            str = String(readPacket.data, 0, readPacket.length, Charsets.UTF_8)

            println(str)

            // I tried to update textview in here but the exception occurs
            //textView1.setText(str)

        } catch (e: Exception) {
           println("open fun receiveUDP catch exception.$e")
           e.printStackTrace()
        }
//        finally {
//           readSocket?.close()
//        }

    }
}

我应该怎么做才能向 TextView 显示“str”?

这是堆栈跟踪:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()” 在 android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173) 在 android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174) 在 android.content.Context.obtainStyledAttributes(Context.java:744) 在 androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:839) 在 androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806) 在 androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630) 在 androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223) 在 com.example.socketclientkotlin.UdpDataArrival._$_findCachedViewById(未知来源:25) 在 com.example.socketclientkotlin.UdpDataArrival$receiveUDP$1.run(MainActivity.kt:78) 在 android.os.Handler.handleCallback(Handler.java:938) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:223) 在 android.app.ActivityThread.main(ActivityThread.java:7656) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

【问题讨论】:

  • 请发布您的堆栈跟踪
  • @a_local_nobody 发布它
  • 你尝试在顶层创建一个 lateinit var 吗?
  • 尝试将val textView = findViewById&lt;TextView&gt;(R.id.textView1) 移到线程代码上方
  • @a_local_nobody 对不起,我真的不知道如何改变它..

标签: android kotlin


【解决方案1】:

添加 UI 线程环绕 settext 或访问 UI 线程内的任何 UI Widget

runOnUiThread {
   textView.setText(str)       
}

【讨论】:

  • 我将该代码放入 fun receiveUDP 但仍然出现错误
【解决方案2】:
runOnUiThread {
   textView.setText("Type your text here")       
}

【讨论】:

    【解决方案3】:

    我解决了它以使“UdpDataArrival”类成为 MainActivity 的内部类 并使用下面的代码,它的工作原理!:

    runOnUiThread {
        textview.setText(str)
    }
    

    谢谢!

    【讨论】:

    • 请点击勾选标记接受帮助您解决问题的答案,而不是发布您自己的答案。