Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

android - How can I update text of TextView in thread using kotlin

I'm receiving UDP data from server and I want to show the UDP data to a TextView. But NullPointerException occurs everytime. I don't know why.

Here is my code:

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!
")

        println("MainActivity onCreate success.")
    }

}

This class is thread to keep receiving UDP data

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()
//        }

    }
}

What should I do to show the 'str' to the TextView?

This is the stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173) at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174) at android.content.Context.obtainStyledAttributes(Context.java:744) at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:839) at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806) at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630) at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223) at com.example.socketclientkotlin.UdpDataArrival._$_findCachedViewById(Unknown Source:25) at com.example.socketclientkotlin.UdpDataArrival$receiveUDP$1.run(MainActivity.kt:78) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

question from:https://stackoverflow.com/questions/65913646/how-can-i-update-text-of-textview-in-thread-using-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

add UI thread surround settext or access any UI Widget inside UI thread

runOnUiThread {
   textView.setText(str)       
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...