简体   繁体   中英

.text does not print anything, yet .append does

private fun testing (data: CharSequence) {
        runOnUiThread{

            test!!.text = data
            textView!!.append(data)
        }
    }

Two different textViews called test and textView. My goal is to use.text to print the data variable to a textView. Unfortunately this doesnt seem to want to work. Strangely.append works, but I want the data to print, then to be overwritten by any new changes.

Image of my app for easier understanding of the situation

Here in the image above you can see that the second textView is working fine with.append. But the textView above that's using.text does not print anything? Why is this

Data variable comes from Arduino Board. Here is my code

var mCallback = UsbReadCallback { arg0 ->
        //Defining a Callback which triggers whenever data is read.
        var data: String? = null
        try {
            data = String(arg0, Charsets.UTF_8)
            "$data/n"
            testing(data)
            tvAppend(textView, data)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
    }

Is this something to do with CharSequence? Can someone help

Here is my XML file:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".Surfboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/surfboard"
    >

        <!--Table Layout with 3 rows and each row with 3 buttons-->
        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:rowCount="3"
            android:columnCount="3"
            android:padding="8dp"
            >

            <Button
                android:id="@+id/buttonStart"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickStart"
                android:text="@string/Begin"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/statusText"
                android:layout_below="@+id/buttonSend"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentBottom="true" />



            <!--Row 1-->
            <TableRow>

                <Button
                    android:id="@+id/b00"
                    style="@style/Widget.AppCompat.Button"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="8dp"
                    android:gravity="center"
                    android:background="@color/colorAccent"
                    android:textColor="#FFFFFF"
                    android:textSize="22sp" />

                <Button
                    android:id="@+id/b01"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_margin="8dp"
                    android:background="@color/colorAccent"
                    android:gravity="center"
                    android:textColor="#FFFFFF"
                    android:textSize="22sp" />

                <Button
                    android:id="@+id/b02"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:textSize="22sp"
                    android:textColor="#FFFFFF"
                    android:background="@color/colorAccent"
                    android:gravity="center"
                    android:layout_margin="8dp"
                    style="@style/Widget.AppCompat.Button"
                    />

            </TableRow>

            <Button
                android:id="@+id/activate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/activate"
                android:onClick="onClickSend"
                tools:ignore="OnClick" />

            <Button
                android:id="@+id/deactivate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickStop"
                android:text="@string/deactivate"/>

            <TextView
                android:id="@+id/test"
                android:layout_width="wrap_content"
                android:background="#E0E0E0"
                android:layout_height="wrap_content"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView"
                android:layout_below="@+id/buttonSend"
                android:layout_marginTop="20dp"
                android:background="#E0E0E0" />

        </TableLayout>

</RelativeLayout>

Here is me initiating the TextViews:

var textView: TextView? = null
var textView2: TextView? = null

textView = findViewById<View>(R.id.textView) as TextView
 textView2 = findViewById<View>(R.id.test) as TextView

Here is also a video to help explain: https://youtu.be/LaMsjB7v5WI

Here is my tvAppend:

private fun tvAppend(tv: TextView?, text: CharSequence) {
    runOnUiThread {
        //tv!!.append(text)
     }
}

Basically the same as the function testing(). This is not doing anything, I have commented out the action.

Perhaps i should provide all my code:

package com.example.surf10

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_surfboard.*

import android.app.Activity
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.util.Log
import android.widget.EditText
import android.widget.TextView
import com.felhr.usbserial.UsbSerialDevice
import com.felhr.usbserial.UsbSerialInterface
import com.felhr.usbserial.UsbSerialInterface.UsbReadCallback
import kotlinx.android.synthetic.main.activity_surf_board2.*
import java.io.UnsupportedEncodingException



class Surfboard : AppCompatActivity() {

    val ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION"
    var startButton: Button? = null
    var sendButton: Button? = null
    var stopButton: Button? = null
    var textView: TextView? = null
    var textView2: TextView? = null
    var statusText: TextView? = null
    var usbManager: UsbManager? = null
    var device: UsbDevice? = null
    var serialPort: UsbSerialDevice? = null
    var connection: UsbDeviceConnection? = null



    var mCallback = UsbReadCallback { arg0 ->
        //Defining a Callback which triggers whenever data is read.
        var data: String? = null
        try {
            data = String(arg0, Charsets.UTF_8)
            "$data/n"
            testing(data)
            tvAppend(textView, data)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
    }

    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        //Broadcast Receiver to automatically start and stop the Serial connection.
        override fun onReceive(
            context: Context,
            intent: Intent
        ) {
            if (intent.action == ACTION_USB_PERMISSION) {
                val granted = intent.extras!!.getBoolean(
                    UsbManager.EXTRA_PERMISSION_GRANTED
                )
                if (granted) {
                    connection = usbManager!!.openDevice(device)
                    serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection)
                    if (serialPort != null) {
                        if (serialPort!!.open()) { //Set Serial Connection Parameters.
                            setUiEnabled(true)
                            serialPort!!.setBaudRate(9600)
                            serialPort!!.setDataBits(UsbSerialInterface.DATA_BITS_8)
                            serialPort!!.setStopBits(UsbSerialInterface.STOP_BITS_1)
                            serialPort!!.setParity(UsbSerialInterface.PARITY_NONE)
                            serialPort!!.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF)
                            serialPort!!.read(mCallback)
                            tvAppend(statusText, "Serial Connection Opened!\n")
                        } else {
                            Log.d("SERIAL", "PORT NOT OPEN")
                        }
                    } else {
                        Log.d("SERIAL", "PORT IS NULL")
                    }
                } else {
                    Log.d("SERIAL", "PERM NOT GRANTED")
                }
            } else if (intent.action == UsbManager.ACTION_USB_DEVICE_ATTACHED) {
                onClickStart(startButton)
            } else if (intent.action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
                onClickStop(stopButton)
            }
        }
    }

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

        usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        startButton = findViewById<View>(R.id.buttonStart) as Button
        sendButton = findViewById<View>(R.id.activate) as Button
        stopButton = findViewById<View>(R.id.deactivate) as Button
        textView = findViewById<View>(R.id.textView) as TextView
        textView2 = findViewById<View>(R.id.test) as TextView
        statusText = findViewById<View>(R.id.statusText) as TextView

        setUiEnabled(false)
        val filter = IntentFilter()
        filter.addAction(ACTION_USB_PERMISSION)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        registerReceiver(broadcastReceiver, filter)

    }

    fun setUiEnabled(bool: Boolean) {
        startButton!!.isEnabled = !bool
        sendButton!!.isEnabled = bool
        stopButton!!.isEnabled = bool
        textView!!.isEnabled = bool
        textView2!!.isEnabled = bool
    }

    fun onClickStart(@Suppress("UNUSED_PARAMETER")view: View?) {
        val usbDevices = usbManager!!.deviceList
        if (!usbDevices.isEmpty()) {
            var keep = true
            for ((_, value) in usbDevices) {
                device = value
                val deviceVID = device!!.vendorId
                if (deviceVID == 0x2341) //Arduino Vendor ID
                {
                    val pi =
                        PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
                    usbManager!!.requestPermission(device, pi)
                    keep = false
                } else {
                    connection = null
                    device = null
                }
                if (!keep) break
            }
        }
    }

    fun onClickSend(@Suppress("UNUSED_PARAMETER")view: View?) {
        val string = "g"
        serialPort!!.write(string.toByteArray())
        //tvAppend(textView, "\nData Sent : " + string)
    }

    fun onClickStop(@Suppress("UNUSED_PARAMETER")view: View?) {
        setUiEnabled(false)
        serialPort!!.close()
        tvAppend(textView, "\nSerial Connection Closed! \n")
    }

    private fun tvAppend(tv: TextView?, text: CharSequence) {
        runOnUiThread {
            //tv!!.append(text)
         }
    }

    private fun testing (data: CharSequence) {



        runOnUiThread{
            textView!!.text = data.toString() <---- THIS DOES NOT WORK

            textView2!!.append(data)
        }
    }


}
private fun testing (data: CharSequence) {
    runOnUiThread {
        test!!.text = data.toString()  <<<<<--- Edited
        textView!!.text = data.toString()   
    }
}

ok now i think i understand your question

you need to cast data:CharSequence to String first by doing.toString() and someTextView.text is also CharSequence meaning if you want to use test...text value as String you need to cast it to .toString

so

 test!!.text = data.toString()
 textView!!.text = test!!.text.toString()

this is an example if you want to change something on test.!.text first

private fun testing (data: CharSequence) {
var castDataToString = data.toString()
test!!.text = castDataToString
castDataToString = "New vaule"
textView!!.text = castDataToString 
}

or actually you can change to be like this

    private fun testing (data: String) {

            test!!.text = data
            var changedText : String = test!!.text.toString()
//or  var changedText = data   since it's the same as text!!.text.toString()

            changedText = "change to something you want"
            textView!!.text = changedText

    }

since method testing receive parameter as String already so you don't need to cast it inside again but remember if you want to get string value from someTextView you need to call someTextView.text.toString()

private fun testing (data: CharSequence) {

    runOnUiThread {
Log.d("Test Function","on testing function call")
        test!!.text = data.toString()  <<<<<--- Edited
        textView!!.text = data.toString()   
    }
}

could you log this function to see if it really call this function when you click button

sorry for late replay could you try this again to see if it work

first remove this import

import kotlinx.android.synthetic.main.activity_surf_board2.*

and see run again to see if it still work

after that

private fun tvAppend(tv: TextView?, text: CharSequence) {
        runOnUiThread {
            test.text = text.toString()  <----- add this line
            tv!!.append(text)
         }
    }



fun onClickSend(@Suppress("UNUSED_PARAMETER")view: View?) {
        val string = "g"
        serialPort!!.write(string.toByteArray())
        tvAppend(textView, "\nData Sent : " + string)
    }

and run again now it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM