0

In the below code which is for bluetooth messaging with arduino i am trying to change color on some static strings. 1.On the start button listener i have a message"Connection opened" which i am changing color using the xml file and creating there a string with specific color. This method works only there. 2. i tried another method with spannable string on the send button listener but is not working at all the message comes in black. what i want to to do is that when i send a message on my textview i see the "send data: "+ string(msg i send) and i want this send data to be red for examle and the same for the receive one. What i tried untill now is on the code.If there is any idea to try i will be grateful.

public class MainActivity extends Activity {
    
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
    private BluetoothDevice device;
    private BluetoothSocket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    Button startButton, sendButton,clearButton,stopButton;
    TextView textView;
    EditText editText;
    boolean deviceConnected=false;
    //Thread thread;
    byte[] buffer;
    //int bufferPosition;
    boolean stopThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = findViewById(R.id.buttonStart);
        sendButton = findViewById(R.id.buttonSend);
        clearButton = findViewById(R.id.buttonClear);
        stopButton = findViewById(R.id.buttonStop);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        textView.setMovementMethod(new ScrollingMovementMethod());
        setUiEnabled(false);

        startButton.setOnClickListener(v -> {

            if(BTinit())
            {
                if(BTconnect())
                {
                    setUiEnabled(true);
                    deviceConnected=true;
                    beginListenForData();
                    //textView.append("Connection Opened!");
                    String greenString = getResources().getString(R.string.Connection_Opened);
                    textView.append(Html.fromHtml(greenString));
                }

            }
        });
        sendButton.setOnClickListener(v -> {

            String t = "Send Data: ";
            SpannableString spannableString = new SpannableString(t);
            ForegroundColorSpan green = new ForegroundColorSpan(getResources().getColor(R.color.private_green));
            spannableString.setSpan(green, 0, 9, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

            String string = editText.getText().toString();
            String str = string.concat("\n");
            try {
                outputStream.write(str.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            textView.append(spannableString + str);
        });
        stopButton.setOnClickListener(v -> {
            try {
                stopThread = true;
                outputStream.close();
                inputStream.close();
                socket.close();
                setUiEnabled(false);
                deviceConnected=false;
                textView.append("Connection Closed!");
            }catch (IOException e){
                e.printStackTrace();
            }
        });
        clearButton.setOnClickListener(v -> textView.setText(""));
    }

    public void setUiEnabled(boolean bool)
    {
        startButton.setEnabled(!bool);
        sendButton.setEnabled(bool);
        stopButton.setEnabled(bool);
        textView.setEnabled(bool);

    }

    public boolean BTinit()
    {
        boolean found=false;
        BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
        }
        if(bluetoothAdapter !=null)
        {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);
        }
        assert bluetoothAdapter != null;
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if(bondedDevices.isEmpty())
        {
            Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
        }
        else
        {
            for (BluetoothDevice iterator : bondedDevices)
            {
                //private final String DEVICE_NAME="ArduinoBT";
                String DEVICE_ADDRESS = "98:DA:C0:00:2C:E2";
                if(iterator.getAddress().equals(DEVICE_ADDRESS))
                {
                    device=iterator;
                    found=true;
                    break;
                }
            }
        }
        return found;
    }

    public boolean BTconnect()
    {
        boolean connected=true;
        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            connected=false;
        }
        if(connected)
        {
            try {
                outputStream=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream=socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        return connected;
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        stopThread = false;
        buffer = new byte[1024];
        Thread thread  = new Thread(() -> {
            while(!Thread.currentThread().isInterrupted() && !stopThread)
            {
                try
                {
                    int byteCount = inputStream.available();
                    if(byteCount > 0)
                    {
                        byte[] rawBytes = new byte[byteCount];
                        inputStream.read(rawBytes);
                        final String string=new String(rawBytes, StandardCharsets.UTF_8);
                        handler.post(() -> textView.append("Receive data: " + string));

                    }
                }
                catch (IOException ex)
                {
                    stopThread = true;
                }
            }
        });

        thread.start();
    }
}
Zain
  • 37,492
  • 7
  • 60
  • 84
Nikolas
  • 13
  • 4

1 Answers1

0

Try like this;

Spannable text = new SpannableString("Send Data:");        

text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.private_green)), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
RaBaKa 78
  • 1,115
  • 7
  • 11