活动更改时,BluetoothSocket.getInputStream()会导致NullPointerException

时间:2018-07-26 17:34:41

标签: java android android-activity

我正在编写一个与蓝牙设备连接并在它们之间交换数据的应用程序。

我对“活动”更改有疑问。

当应用程序启动并创建Bluetooth套接字时,我可以发送消息,但是当我进入第二个Activity然后返回到第一个Activity时,单击按钮sendMessage会出现以下错误:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()'

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nawigacja);
    Intent newInt = getIntent();
    address = newInt.getStringExtra(Lista.EXTRA_ADDRESS);
    if (savedInstanceState != null){
        address = savedInstanceState.getString("adress");
    }
    IntCzasOsob = newInt.getStringExtra(ConfigAlg1.EXTRA_CZAS_OSOB);
    IntCzasTrwania = newInt.getStringExtra(ConfigAlg1.EXTRA_CZAS_TRWANIA);
    IntCzasBezpieczeństwa = newInt.getStringExtra(ConfigAlg1.EXTRA_CZAS_BEZPIECZENSTWA);
    alg1 = findViewById(R.id.alg1);
    alg2 = findViewById(R.id.alg2);
    button3 = findViewById(R.id.button3);
    BTon = findViewById(R.id.BTon);
}

private void msg(String s) {
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}

private class ConnectBT extends AsyncTask <Void, Void, BluetoothSocket> {
    private boolean ConnectSuccess = true;

    @Override
    protected void onPreExecute() {
        progress = ProgressDialog.show(Nawigacja.this, "Nawiązywanie połączenia...", "Proszę czekać!!!");
    }

    @Override
    protected BluetoothSocket doInBackground(Void... devices) {
        try {
            if (btSocket == null || !isBtConnected) {
                myBluetooth = BluetoothAdapter.getDefaultAdapter();
                BluetoothDevice device = myBluetooth.getRemoteDevice(address);
                btSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID);
                BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                btSocket.connect();
            }
        } catch (IOException e) {
            ConnectSuccess = false;
        }
        return btSocket;
    }

    protected void onPostExecute(BluetoothSocket result) {
        super.onPostExecute(result);

        if (!ConnectSuccess) {
            msg("Brak połączenia.");
            // Intent i = new Intent(Nawigacja.this, Lista.class);
            // startActivity(i);
        } else {
            msg("Połączono.");
            isBtConnected = true;
        }
        progress.dismiss();
    }
}
public void btn3(View view) {
    Intent i = new Intent(Nawigacja.this, ConfigAlg1.class);
    startActivity(i);

}
public void BTon(View view){
    new ConnectBT().execute();
}

public void runAlg1(View view) throws IOException {


    String algorytm1 = "salg1\r\n";
    sendMessage(algorytm1);
    msg("wysłano sAlg1");

}
public void runAlg2(View view) throws IOException {
    String algorytm2 = "salg2\r\n";
    sendMessage(algorytm2);
    msg("wysłano sAlg2");

}
public void runAlg3 (View view){
    msg("onLed" + IntCzasTrwania);
    msg("onLed" + IntCzasOsob);
    msg("onLed" + IntCzasBezpieczeństwa);

}

public class ConnectedThread extends Thread {

    private final InputStream inStream;
    private final OutputStream outStream;


    @RequiresApi(api = Build.VERSION_CODES.ECLAIR)
    public ConnectedThread(BluetoothSocket Socket) {
        InputStream inS = null;
        OutputStream outS = null;

        try {
            inS = Socket.getInputStream();
            outS = Socket.getOutputStream();
        } catch (IOException e) {
            System.out.println("Przerwano");
        }
        inStream = inS;
        outStream = outS;
    }


    public void write(byte[] buffer) {
        try {
            if(btSocket != null){
                btSocket.connect();
            }
            outStream.write(buffer);
            // Share the sent message back to the UI Activity
            mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
             .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }
}
public void sendMessage(String message) throws IOException {
    ConnectedThread ct = new ConnectedThread(btSocket);
    byte[] send = message.getBytes();
    ct.write(send);
}
public void write(byte[] out) {
    ConnectedThread ct = new ConnectedThread(btSocket);
    Log.d(TAG, "...Przesyłanie: " + out + "...");
    ct.write(out);
}
private final Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what){
            case Constants.MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                String[] wm = new String[1];
                wm[1] = writeMessage;
                break;
            case Constants.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                String[] rm = new String[1];
                rm[1] = readMessage;
                break;
        }
    }
};

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString("adress", address);
    super.onSaveInstanceState(savedInstanceState);
}

}

java.lang.IllegalStateException: Could not execute method for android:onClick
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
    at android.view.View.performClick(View.java:6256)
    at android.view.View$PerformClick.run(View.java:24704)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6590)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
    at android.view.View.performClick(View.java:6256) 
    at android.view.View$PerformClick.run(View.java:24704) 
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6590) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()' on a null object reference
    at irko.iot4home.Nawigacja$ConnectedThread.<init>(Nawigacja.java:143)
    at irko.iot4home.Nawigacja.sendMessage(Nawigacja.java:168)
    at irko.iot4home.Nawigacja.runAlg1(Nawigacja.java:114)
    at java.lang.reflect.Method.invoke(Native Method) 
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
    at android.view.View.performClick(View.java:6256) 
    at android.view.View$PerformClick.run(View.java:24704) 
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6590) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)  

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

去参加另一项活动时,请闭门造车! 当您返回上一个活动时,流已关闭,但您尝试使用它们写入数据