1
I have a Java code that I adapted to receive a string via bluetooth and when running it in Android Studio does not present errors. However, in the app by clicking the "Start" button to go to Main2activity (Where the code in question is), it shows the error "App X stopped".
Below is the code, in case someone can help me or has another example that I can use it, thank you.
Note: The bluetooth connection is working smoothly.
package com.hlp.bluetoothfinal;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main2Activity extends AppCompatActivity {
private EditText textView;
private EditText textView2;
private static final int MESSAGE_READ = 3;
ConnectedThread connectedThread;
Handler mHandler;
StringBuilder dadosBluetooth = new StringBuilder( );
@SuppressLint( "WrongViewCast" )
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main2 );
textView = (EditText) findViewById( R.id.textView );
textView2 = (EditText) findViewById( R.id.textView2 );
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
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
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);
textView.setText(dadosFinais);
}
dadosBluetooth.delete(0, dadosBluetooth.length());
}
}
}
};
You can’t tell what the problem is. We need more information, for example which versions of the SDK the code was compiled and executed on, emulated and tested device models, emulator bug and alert reports, and device bug and alert reports.
– Augusto Vasques