Quando tento usar o método write a partir da Activity principal ocorre o erro
MainActivity
`
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 123;
private static final int REQUEST_MICROPHONE = 456;
Bt_connect bt_connect;
private static TextView subtitle;
private boolean firstTime = true;
public static Context context;
private SpeechToText stt;
private static TextView statusMessage;
private Button mic_button;
/…
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/ … \
public void onClickEscutar(View view) throws InterruptedException {
Log.i("Text","clicou");
stt.backgroundVoiceListener.run(); // inicia o reconhecedor de voz do android
}
public void onClickBt_connect(View view)throws InterruptedException{
bt_connect = new Bt_connect("98:D3:34:90:F1:41"); // faz a conexão bluetooth
bt_connect.start();
}
public void MsgToArduino(String txt) {
bt_connect.write(txt.getBytes()); // manda a mensagem
}
}
Class Speech Recognizer
public class SpeechToText implements RecognitionListener {
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private MainActivity mainActivity;
private String text = “”;
Bt_connect connect;
private boolean isListening = false;
int MINIMUM_LENGTH_FOR_EXTRA_SPEECH_IN_MILLIS = 2000;
final BackgroundVoiceListener backgroundVoiceListener;
/…
@Override
public void onReadyForSpeech(Bundle bundle) {
setListening(false);
}
@Override
public void onBeginningOfSpeech() {
setListening(true);
}
@Override
public void onRmsChanged(float v) {
Log.i(“Text”, "onRmsChanged: " + v);
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
setListening(false);
}
@Override
public void onError(int i) {
mainActivity.setSubtitle(text);
Log.i("Text","text: " + text);
}
@Override
public void onResults(Bundle bundle) {
}
@Override
public void onPartialResults(Bundle partialResults) {
ArrayList<String> matches = partialResults
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
text = "";
Log.i("Text","text: " + text);
if(matches.size() > 0)
for (String result : matches){
if(result.equalsIgnoreCase("ligar luz")){
mainActivity.MsgToArduino("ligar luz"); // Manda a msg quando o resultado desejado e encontrado
}
}
Log.i("Text","text: " + text);
mainActivity.setSubtitle(text);
setListening(false);
}
@Override
public void onEvent(int i, Bundle bundle) {}
public class BackgroundVoiceListener extends Thread{
public void run(){
try {
this.sleep(2000);
if(!isListening()){
setListening(true);
speech.startListening(recognizerIntent);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Class Conexão Bluetooth
public class Bt_connect extends Thread{
BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
boolean server;
boolean running = false;
boolean isConnected = false;
public Bt_connect() { // construtor modo servidor
this.server = true;
}
public Bt_connect(String btDevAddress) { // construtor modo cliente
this.server = false;
this.btDevAddress = btDevAddress;
}
public void run() {
this.running = true;
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(this.server) {
/* Servidor.
*/
try {
btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("Super Counter", UUID.fromString(myUUID));
btSocket = btServerSocket.accept();
if(btSocket != null) {
btServerSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
}
} else {
/* Cliente.
*/
try {
BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));
btAdapter.cancelDiscovery();
if (btSocket != null) {
btSocket.connect();
}
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
}
}
// conexao pronta
if(btSocket != null) {
this.isConnected = true;
toMainActivity("---S".getBytes());
try {
/*
input = btSocket.getInputStream();
output = btSocket.getOutputStream();
while(running) {
byte[] buffer = new byte[1024];
int bytes;
int bytesRead = -1;
do {
bytes = input.read(buffer, bytesRead+1, 1);
bytesRead+=bytes;
} while(buffer[bytesRead] != '\n');
/* A mensagem recebida é enviada para a Activity principal.
*/
toMainActivity(Arrays.copyOfRange(buffer, 0, bytesRead));
}
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
this.isConnected = false;
}
}
}
private void toMainActivity(byte[] data) {
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putByteArray("data", data);
message.setData(bundle);
MainActivity.handler.sendMessage(message);
}
public void write(byte[] data) { // metodo escreve na conexao bluetooth
if(output != null) {
try {
/* Transmite a mensagem.
*/
output.write(data);
} catch (IOException e) {
e.printStackTrace();
}
} else {
/* Envia à Activity principal um código de erro durante a conexão.
*/
toMainActivity("---N".getBytes());
}
}
public void cancel() {
try {
running = false;
this.isConnected = false;
btServerSocket.close();
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
running = false;
this.isConnected = false;
}
public boolean isConnected() {
return this.isConnected;
}
}
StackTrace
` java.lang.NullPointerException: Attempt to invoke virtual method ‘void skynet.home_control.Bt_connect.write(byte[])’ on a null object reference
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at skynet.home_control.MainActivity.MsgToArduino(MainActivity.java:138)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at skynet.home_control.SpeechToText.onPartialResults(SpeechToText.java:85)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at android.speech.SpeechRecognizer$InternalListener$1.handleMessage(SpeechRecognizer.java:459)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at android.os.Looper.loop(Looper.java:154)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6123)
11-13 20:11:02.509 22970-22970/skynet.home_control W/System.err: at java.lang.reflect.Method.invoke(Native Method)
11-13 20:11:02.510 22970-22970/skynet.home_control W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-13 20:11:02.510 22970-22970/skynet.home_control W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
11``