Search code examples
androidprintingbluetoothbluetooth-printing

Bluetooth printer throws exception after printing 2 times.


I have developed and android application to print the bill from Bluetooth printer, my code throws exception as " java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference ".

My Code for connection the Bluetooth printer and sending the data to print is as bellow:

enter code here

// This will find a bluetooth printer device

void findBT() 
{
    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {
            //myLabel.setText("No bluetooth adapter available");

            Utilities.showToast("No bluetooth adapter available", true);
        }

        if (!mBluetoothAdapter.isEnabled()) 
        {

            Utilities.showToast("Bluetooth is not On, Please Turn on Blueetooth", true);

        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                .getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                //Toast.makeText(PrintMain.this, "Device Name : " + device.getName(), Toast.LENGTH_SHORT).show();

                // MP300 is the name of the bluetooth printer device
                if (device.getName().equals("PTP-III")) {
                    mmDevice = device;
                    break;
                }
            }
        }
        //   myLabel.setText("Bluetooth Device Found");

        Utilities.showToast("Bluetooth Device is Found", true);

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


enter code here

void openBT() throws IOException {
try {
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        //UUID uuid = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        // myLabel.setText("Bluetooth Opened");

        Utilities.showToast("Bluetooth connection is Open now", true);

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enter code here

void beginListenForData() {
    try {
        final Handler handler = new Handler();

        // This is the ASCII code for a newline character
        final byte delimiter = 10;

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];

        workerThread = new Thread(new Runnable() {
            public void run() {
                while (!Thread.currentThread().isInterrupted()
                        && !stopWorker) {

                    try {

                        int bytesAvailable = mmInputStream.available();
                        if (bytesAvailable > 0) {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.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() {
                                            // myLabel.setText(data);
                                        }
                                    });
                                } else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }

                    } catch (IOException ex) {
                        stopWorker = true;
                    }

                }
            }
        });

        workerThread.start();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
enter code here

void sendData(String VoucherNumber, String ConnectedCmpName, String EntryUserName, String PartyName, String VoucherDate, Context mContext1, String[] InvItemDtls ) throws IOException
{

    try
    {
        String StrVisitAgain = "VISIT AGAIN     \n";
        mmOutputStream.write(StrVisitAgain.getBytes());


        mmOutputStream.flush();

    } catch (Exception e) {
        Log.e("Main", "Exe ", e);
        System.out.println("Excelption is : " + e.toString());
    }
}

enter code here

void closeBT() throws IOException {
    try {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        Utilities.showToast("Bluetootj is now Closed", true);
        // myLabel.setText("Bluetooth Closed");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enter code here

// Code to print the data

        PrintSalesInvoice p = new PrintSalesInvoice();
        try {
            p.findBT();
            p.openBT();
            p.sendData(VoucherNumber, ConnectedCmpName, EntryUserName, PartyName, VoucherDate, getApplicationContext(),InvItemDtls);
            p.closeBT();
        } catch (IOException ex) {


        }

Solution

  • Adding the bellow code in SendData Function (function which prints the data) has resolved the issue.

    enter code here
    
    try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }