0

I'm trying to connect my android application to my Arduino Uno by Bluetooth. In order to make the connection general to the whole application, I created a service where I implemented my Bluetooth functions. The problem is that my sendData function is causing an error and don't have any idea on how to resolve it.

Please help me. Thanks in Advance :)

Here is my MainActivity.java :

package llg.trashbin;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import android.content.Intent;


public class MainActivity extends AppCompatActivity {

public int objectOut = 0;
communicationEnabled mCommunicate = new communicationEnabled();

Button bottle, emballages, papier;

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

    Intent mBluetooth = new Intent(MainActivity.this, BluetoothConnectService.class);
    startService(mBluetooth);

    bottle = (Button) findViewById(R.id.bottle);
    emballages = (Button) findViewById(R.id.emballages);
    papier = (Button) findViewById(R.id.papier);

    bottle.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            objectOut = 2;
            mCommunicate.MessageSent();
        }
    });
    emballages.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            objectOut = 3;
            mCommunicate.MessageSent();
        }
    });
    papier.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            objectOut = 5;
            mCommunicate.MessageSent();
        }
    });
}

public class communicationEnabled extends BluetoothConnectService {
    public String hello = "1";

    public void MessageSent() {
        sendData(hello);
    }
}

}

BluetoothConnectService.java :

package llg.trashbin;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;

import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;


public class BluetoothConnectService extends Service {

private static final String TAG = "Tripoubelle";

public static final int REQUEST_ENABLE_BT = 1;
public BluetoothAdapter btAdapter = null;
public BluetoothSocket btSocket = null;
public OutputStream outStream = null;

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "00:13:EF:00:00:4C";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Log.d(TAG, "In onCreate()");
    super.onCreate();
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

    Log.d(TAG, "...In onResume - Attempting client connect...");

    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    btAdapter.cancelDiscovery();
    Log.d(TAG, "...Connecting to Remote...");
    try {
        btSocket.connect();
        Log.d(TAG, "...Connection established and data link opened...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }

    Log.d(TAG, "...Creating Socket...");

    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume(), input and output stream creation failed:" + e.getMessage() + ".");
    }
}


public void onPause() {

    Log.d(TAG, "...In onPause()...");

    if (outStream != null) {
        try {
            outStream.flush();
        } catch (IOException e) {
            errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
        }
    }

    try     {
        btSocket.close();
    } catch (IOException e2) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
}

public void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on

    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
        if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth is enabled...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableBtIntent);
        }
    }
}

private void errorExit(String title, String message){
    Toast msg = Toast.makeText(getBaseContext(),
            title + " - " + message, Toast.LENGTH_SHORT);
    msg.show();
    finish();
}

public void sendData(String message) {
    byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Sending data: " + message + "...");
    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
        if (address.equals("00:13:EF:00:00:4C"))
            msg = msg + ".\n\nUpdate your server address from 00:13:EF:00:00:4C to the correct address on line 37 in the java code";
        msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

        errorExit("Fatal Error", msg);
    }
}

}

Here is the error :

12-27 10:21:52.511 1178-1178/llg.trashbin E/AndroidRuntime: FATAL EXCEPTION: main
Process:    llg.trashbin, PID: 117
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
at llg.trashbin.BluetoothConnectService.sendData(BluetoothConnectService.java:125)
at llg.trashbin.MainActivity$communicationEnabled.MessageSent(MainActivity.java:103)
at llg.trashbin.MainActivity$2.onClick(MainActivity.java:71)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10888)
at android.view.View$PerformClick.run(View.java:22541)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Edit :

I have put the code of sentData function into an if/else statement in order to check if the assigned string were null :

public void sendData(String message) {
    if (message != null) {
        Log.d(TAG, "sent data isn't null !");
        byte[] msgBuffer = message.getBytes();
        Log.d(TAG, "...Sending data: " + message + "...");
        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
            if (address.equals("00:13:EF:00:00:4C"))
                msg = msg + ".\n\nUpdate your server address from 00:13:EF:00:00:4C to the correct address on line 37 in the java code";
            msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

            //errorExit("Fatal Error", msg);
        }
    }
    else {
        Log.d(TAG, "sent data is null !");
    }
}

And I had a positif result : the assigned string weren't null !

Here is the debug window :

12-27 12:53:24.661 8183-8183/llg.trashbin D/Tripoubelle: sent data isn't null !
  • Code that depends on the success of prior code in a `try` block should be inside that `try` block. Often this means that the entire method should throw the exception instead of catching it. Don't write code like this. – user207421 Dec 28 '16 at 04:34

2 Answers2

0

If its not the message variable, then it must be the outputstream. Try doing this in sendData() method

if (message!=null){  
 byte[] msgBuffer = message.getBytes();    
try{
 outStream = btSocket.getOutputStream();  
}  
catch (IOException e) {
          errorExit("Fatal Error", "in sendData() input and output stream creation failed:" + e.getMessage() + ".");

    }  
try {
            outStream.write(message);
        } catch (IOException e) {  
}
Bantu
  • 585
  • 5
  • 12
0

First of all, the stacktrace can say a lot about the actual exception. To understand it you usually want to start from the bottom(which caused the error) to top(what the actual error was).

In you case, the line

java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference

means that the write() method is trying to be called on the object which is null (OutputStream).

I would suggest you to check the output stream object for a null reference first:

if(outStream==null)

then if it is you have to initialize it again

try { outStream = btSocket.getOutputStream(); } catch (IOException e) { errorExit("Fatal Error", "In onResume(), input and output stream creation failed:" + e.getMessage() + "."); }

szholdiyarov
  • 385
  • 2
  • 12