Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Application is crashing after return to the previous layout

I have troubles with my application which is connecting with arduino throught bluetooth module. If user won't connect to arduino and he wants to come back to the previous layout the application will crash. Everything is okay if user will connect to arduino and then press back on the phone.

Here is java code of the main layout package com.example.aei.coffeeoclock;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {

Button makeCoffe;
Button Authors;

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

    makeCoffe = findViewById(R.id.make_coffe); //
    makeCoffe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openCoffeeMaker();
        }
    });

    Authors = findViewById(R.id.authors);
    Authors.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openAuthors();
        }
    });
}

public void openCoffeeMaker() {
    Intent intent = new Intent(this, Final.class);
    startActivity(intent);
}

public void openAuthors() {
    Intent intent = new Intent(this, Authors.class);
    startActivity(intent);
}

}

Here is java code of the Final.class:

public class Final extends AppCompatActivity {

//BLUETOOTH
TextView Result;
public String dataToSend;
public int connected=0;

public static final String TAG = "Jon";
public BluetoothAdapter mBluetoothAdapter = null;
public BluetoothSocket btSocket = null;
public OutputStream outStream = null;
public static String address = "98:D3:31:08:21:E6";
public static final UUID MY_UUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");
public InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final);

    Connected = findViewById(R.id.connected);
    ChoosenCoffee = findViewById(R.id.choosen_coffee);
    Error = findViewById(R.id.error);

    CheckBt();

    Connect = findViewById(R.id.connect);
    Connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(connected%2 == 0) {
                Connect();
                Connected.setText("POŁĄCZONO");
                connected_value = "polaczono";
                Connected.setTextColor(Color.GREEN);
                dataToSend = "a";
                writeData(dataToSend);

                Connect.setText("ROZŁĄCZ");
                connected++;
            }
            else
            {
                dataToSend = "b";
                writeData(dataToSend);

                DisconnectBluetooth();
                Connected.setText("ROZŁĄCZONO");
                connected_value = "rozlaczono";
                Connected.setTextColor(Color.RED);

                Connect.setText("POŁĄCZ");
                connected++;
            }
        }
    });


private void CheckBt() {

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
        } else if (mBluetoothAdapter == null) {
        Error.setText("Urządzenienie nie posiada bluetooth.");
        } else {
        Error.setText("");
    }
}

public void Connect() {
    Log.d(TAG, address);
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.d(TAG, "Connecting to ... " + device);
    mBluetoothAdapter.cancelDiscovery();
    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        btSocket.connect();
        Log.d(TAG, "Connection made.");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            Log.d(TAG, "Unable to end the connection");
        }
        Log.d(TAG, "Socket creation failed");
    }

    beginListenForData();
}

private void writeData(String data) {
    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        Log.d(TAG, "Bug BEFORE Sending stuff", e);
    }

    String message = data;
    byte[] msgBuffer = message.getBytes();

    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        Log.d(TAG, "Bug while sending stuff", e);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();

    try {
        btSocket.close();
    } catch (IOException e) {
    }
}

public void beginListenForData()   {
    try {
        inStream = btSocket.getInputStream();
    } catch (IOException e) {
    }
    Thread workerThread = new Thread(new Runnable()
    {
        public void run()
        {
            while(!Thread.currentThread().isInterrupted() && !stopWorker)
            {
                try
                {
                    int bytesAvailable = inStream.available();
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        inStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];
                            if(b == delimiter)
                            {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                readBufferPosition = 0;
                                handler.post(new Runnable()
                                {
                                    public void run()
                                    {
                                        if(Result.getText().toString().equals("..")) {
                                            Result.setText(data);
                                        } else {
                                            Result.append("\n"+data);
                                        }
                                    }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    stopWorker = true;
                }
            }
        }
    });
    workerThread.start();
}

private void DisconnectBluetooth() {
    if (inStream != null) {
        try {inStream.close();} catch (Exception e) {}
        inStream = null;
    }

    if (outStream != null) {
        try {outStream.close();} catch (Exception e) {}
        outStream = null;
    }

    if (btSocket != null) {
        try {btSocket.close();} catch (Exception e) {}
        btSocket = null;
    }
}
}

Comments