Split no Android Studio - Java

Sou iniciante em programação Java e no meu código recebo por meio da comunicação bluetooth 8 strings, elas estão separadas por virgulas e desejo “pegar” cada uma delas para printar em uma caixa de texto. Estou tentando utilizar o Split, mas parece que não reconhece essa opção, pois a palavra fica em vermelho. Alguém poderia me ajudar?

public class MainActivity extends AppCompatActivity {

    Button btnConexao, btn2, btn3, btn6;

    private static final int SOLICITA_ATIVACAO = 1;
    private static final int SOLICITA_CONEXAO = 2;
    private static final int MESSAGE_READ = 3;

    ConnectedThread connectedThread;

    private EditText textV;


    Handler mHandler;
    StringBuilder dadosBluetooth = new StringBuilder( );
    //StringBuilder acumular os dados recebidos do bluetooth

    private BluetoothAdapter meuBluetoothAdapter = null;
    BluetoothDevice meuDevice = null;
    BluetoothSocket meuSocket = null;
    private BluetoothManager meuManager = null;


    public MainActivity() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        conexao = false;
    }


    private BluetoothAdapter tmp;
    private BluetoothAdapter connect;



    boolean conexao;

    public static String MAC = null;

    UUID MEU_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    public static MainActivity getInstance(Object o, boolean b) {

        return null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        meuBluetoothAdapter = bluetoothManager.getAdapter();

        // Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }


//        btnConexao = (Button)findViewById(R.id.btnConexao);
        //btn3 = (Button)findViewById(R.id.btn3);
        btn2 = (Button)findViewById(R.id.btn2);


       /* btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(i);

            }
        });
*/
        meuBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // Codigo para a conexão bluetooth

        if(meuBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "Seu dispositivo não possui bluetooth", Toast.LENGTH_LONG).show();
        }    else if(!meuBluetoothAdapter.isEnabled())   {
            Intent ativaBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // acao para verficar se o bluetooth esta ativado
            startActivityForResult(ativaBluetooth, SOLICITA_ATIVACAO);
        }


        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (conexao) {
                    //desconectar
                    try {
                        meuSocket.close();
                        conexao = false;
                        btn2.setText("Conectar");
                        Toast.makeText(MainActivity.this.getApplicationContext(), "Bluetooth foi desconectado", Toast.LENGTH_LONG).show();
                    } catch (IOException erro) {
                        Toast.makeText(MainActivity.this.getApplicationContext(), "Ocorreu um erro: " + erro, Toast.LENGTH_LONG).show();

                    }

                } else {
                    //conectar
                    Intent abreLista = new Intent(MainActivity.this, ListaDispositivos.class);
                    MainActivity.this.startActivityForResult(abreLista, SOLICITA_CONEXAO);
                }
            }
        });

// Teste uma leitura


        mHandler = new Handler(  ){ // Função

            @Override
            public void handleMessage(@NonNull Message msg) { //metodo


                if(msg.what == MESSAGE_READ) { //

                    String recebidos = (String) msg.obj; // receber dado em tempo real

                    dadosBluetooth.append(recebidos); // juntar dados

                    int fimInformacao = dadosBluetooth.indexOf("}"); //vendo se a informação está completa

                    if(fimInformacao > 0){ // chegou o final

                        String dadosCompletos = dadosBluetooth.substring(0, fimInformacao ); //dadosCompletos, verifica se tem o inicio { e o fim }

                        int tamInformacao = dadosCompletos.length(); // capturando o tamanho inteiro da informação

                        int tam = dadosBluetooth.length();
                        int indice = dadosBluetooth.indexOf("{");
                        String dados = dadosBluetooth.substring(indice, tam-indice );

                        int indice2 = dados.indexOf("}");

                        String dados2 = dados.substring(1,indice2);


                        String s = dadosBluetooth.toString();

                        char c = s.charAt( indice+1 );
                        
                        String [] textoSeparado = dadosBluetooth.split(",");

                        System.out.println( Arrays.toString(textoSepardo));

                        textV.setText(dados2);

                        if(dadosBluetooth.charAt(0) == '{') {  // se a posição zero for igual { então

                            String dadosFinais = dadosBluetooth.substring(1, tamInformacao); // a dados finais recebe desde a posição 1 até o tamanho da informação

                            //Log.d("Recebidos", dadosFinais);



                            textV.setText(dados2);


                        }

                        dadosBluetooth.delete(0, dadosBluetooth.length());
                    }
                }
            }

        };


    }
    // Fim codigo para a conexao bluetooth

    // Codigo para ativar o bluetooth
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        // super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case SOLICITA_ATIVACAO:
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(getApplicationContext(), "O bluetooth foi ativado", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(getApplicationContext(), "O bluetooth não foi ativado, o app será encerrado", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;

            case SOLICITA_CONEXAO:
                if (resultCode == Activity.RESULT_OK) {
                    MAC = data.getExtras().getString(ListaDispositivos.ENDERECO_MAC);

                    Toast.makeText(getApplicationContext(), "MAC FINAL: " + MAC, Toast.LENGTH_LONG).show();

                    meuDevice = meuBluetoothAdapter.getRemoteDevice(MAC);

                    try {
                        meuSocket = meuDevice.createRfcommSocketToServiceRecord(MEU_UUID);

                        meuSocket.connect();

                        conexao = true;

                        connectedThread = new ConnectedThread( meuSocket );
                        connectedThread.start();

                        btn2.setText("Desconectar");

                        Toast.makeText(getApplicationContext(), "Você foi conectado com:" + MAC, Toast.LENGTH_LONG).show();

                    } catch (IOException erro) {

                        conexao = false;
                        Toast.makeText(getApplicationContext(), "Ocorreu um erro " + erro, Toast.LENGTH_LONG).show();

                    }

                } else {
                    Toast.makeText(getApplicationContext(), "Falha ao obter o MAC", Toast.LENGTH_LONG).show();

                }

        }
    }

    // Fim do codigo para ativar o bluetooth

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_activity,menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){
            case R.id.menu1:
                Toast.makeText(this, "Menu1", Toast.LENGTH_SHORT).show();
                break;

            case R.id.menu2:
                Toast.makeText(this, "Menu2", Toast.LENGTH_SHORT).show();
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    private LeDeviceListAdapter leDeviceListAdapter;

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback leScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            leDeviceListAdapter.addDevice(device);
                            leDeviceListAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };

    public BufferedReader getmBufferedReader() {

        return null;
    }

    public BluetoothSocket getConection() {

        return null;
    }

    //Inicia o recebimento das informações
    private class ConnectedThread extends Thread {
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;


            public ConnectedThread(BluetoothSocket socket) {

                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the input and output streams; using temp objects because
                // member streams are final.
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) { }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {
                byte[] buffer = new byte[1024];
                int bytes; // bytes returned from read()

                // Keep listening to the InputStream until an exception occurs.
                while (true) {
                    try {
                        // Read from the InputStream.
                        bytes = mmInStream.read(buffer);

                        String dadosBt = new String(buffer, 0, bytes); //Objeto - Transforma os bytes em string

                        //Send the obtained bytes to the UI activity.
                        mHandler.obtainMessage(MESSAGE_READ, bytes, -1, dadosBt).sendToTarget();

                        //mHandler é um componente do próprio android que é responsável por trabalhar em segundo plano e evitar que trave.
                        //MESSAGE_READ dados que vem do bluetooth

                    } catch (IOException e) {
                        break;
                    }


                }
            }

            // Call this from the main activity to send data to the remote device.
            public void enviar (String dadosEnviar) {
                byte[]msgBuffer = dadosEnviar.getBytes();
                try {
                    mmOutStream.write(msgBuffer);

                } catch (IOException e) {

                }
            }

        }
    }

Só fica em vermelho? Pode ser que o android studio esteja com erro. Em geral, pode ocorrer, mas o funcionamento é normal.

@Poliana_Alves o erro é pq você esta dando split na variavel dadosBluetooth, e dadosBluetooh é do tipo StringBuilder.

Duas linhas acima você converteu o StringBuilder para String:

É nessa variável s que você deve dar o split, pois quem tem o método split é a classe String e não StringBuilder.

1 curtida