尝试通过蓝牙发送字符串时出现问题

时间:2018-10-09 02:41:53

标签: android bluetooth

因此,我尝试遵循Android Studio教程,了解如何制作蓝牙聊天应用程序,但是做了一些修改以适合我的项目。但是我不是一个聪明的人,对本教程一无所知,只是尝试遵循并复制足够的代码以使其正常工作。

这是代码:

BluetoothDevice mBTDevice;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();


BluetoothAdapter mBluetoothAdapter;

private OutputStream outputStream;
private InputStream inStream;
private int position;


BluetoothConnectionService mBluetoothConnection;

private static final UUID MY_UUID_INSECURE =
        UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");



/*

 */

private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
            BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //3 cases:

            // I think I need just case1
            //case1: bonded already
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
                Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
                mBTDevice = mDevice;
            }
            //case2: creating a bond
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
            }
            //case3: breaking a bond
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
            }
        }
    }
};


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

    GlobalVariables.setmDatabaseHelper(new DatabaseHelper(this));

    /*
    bluetooth tuto
     */

    mBTDevices = new ArrayList<>();

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver4, filter);

    /*
    Calling objects
     */

    buttonAdd = (Button) findViewById(R.id.buttonAdd);
    buttonNewPill = (Button) findViewById(R.id.buttonNewPill);
    buttonSend = (Button) findViewById(R.id.buttonSend);

    editText = (EditText) findViewById(R.id.editText);
    editText2 = (EditText) findViewById(R.id.editText2);
    editText3 = (EditText) findViewById(R.id.editText3);

    spinner = (Spinner) findViewById(R.id.spinner);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner3 = (Spinner) findViewById(R.id.spinner3);

    GlobalVariables.setmDatabaseHelper(new DatabaseHelper(this));
    mDatabaseHelper = GlobalVariables.getmDatabaseHelper();

    /*
    RecyclerView Popualtor
     */

    recycler = (RecyclerView) findViewById(R.id.recyclerView);
    recycler.setLayoutManager(new LinearLayoutManager(this));

    listDatos = new ArrayList<>();

    /*
    Adapters for spinners
     */

    ArrayAdapter<CharSequence> adapterh = ArrayAdapter.createFromResource(this,
            R.array.string_h, android.R.layout.simple_spinner_item);

    ArrayAdapter<CharSequence> adapterm = ArrayAdapter.createFromResource(this,
            R.array.string_m, android.R.layout.simple_spinner_item);

    adapterh.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapterm.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner2.setAdapter(adapterh);
    spinner3.setAdapter(adapterm);

    spinner2.setOnItemSelectedListener(this);
    spinner3.setOnItemSelectedListener(this);

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            recycler.setAdapter(new AdapterDatos(PillVO.getPills(spinner.getSelectedItem().toString())));
            String name = spinner.getSelectedItem().toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    /*
    Bluetooth test
     */


    /*
    Listeners for btns
     */


    buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String newEntry = editText.getText().toString();

            if (editText.length() > 0) {
                AddData(newEntry);
                editText.setText("");
            } else {
                toastMessage("Isn't your field empty?");
            }

        }
    });

    buttonNewPill.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String pill_name = editText2.getText().toString();
            String pill_module = editText3.getText().toString();

            String textSp1 = spinner2.getSelectedItem().toString();
            String textSp2 = spinner3.getSelectedItem().toString();
            String horario = textSp1 + ":" + textSp2;

            String name = spinner.getSelectedItem().toString();

            if (editText2.length() > 0 && editText3.length() > 0) {

                Integer intNewEntry2 = Integer.parseInt(pill_module);

                if (intNewEntry2 <= 10) {

                    PillVO newPill = new PillVO(pill_module, pill_name, horario, name);
                    newPill.save();

                    editText2.setText("");
                    editText3.setText("");

                    recycler.setAdapter(new AdapterDatos(PillVO.getPills(spinner.getSelectedItem().toString())));

                } else {
                    toastMessage("Solo hay 10 modulos");
                }

            } else {
                toastMessage("Todos los campos deben ser completados");
            }

        }
    });

    /*
    Button bluetooth
     */

    buttonSend.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        @Override
        public void onClick(View v) {

            /*
            Collector of Pills
            */

            String shower = "";

            ArrayList<PillVO> list = PillVO.getPills(spinner.getSelectedItem().toString());

            for (PillVO p : list) {

                shower += p.getModulo() + ", " + p.getHorario() + "; ";

            }


            // tuto send

            // if "bytes" doesnt work it might be because of charset
            //byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());

            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);

            enableDisableBT();

            startConnection();


            //sending string

            byte[] bytes = shower.toString().getBytes();
            mBluetoothConnection.write(bytes);

        }


    });

    loadSpinnerData();
}

///bt tuto

private void startConnection() {
    startBTConnection(mBTDevice, MY_UUID_INSECURE);
}

public void startBTConnection(BluetoothDevice device, UUID uuid) {
    Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");

    mBluetoothConnection.StartClient(device, uuid);
}

/// tuto, not needed?

public void enableDisableBT() {
    if (mBluetoothAdapter == null) {
        Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");

    }
    if (!mBluetoothAdapter.isEnabled()) {

        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(enableBTIntent);
    }


}


public void AddData(String newEntry) {
    boolean insertData = mDatabaseHelper.addData(newEntry);

    if (insertData) {
        toastMessage("Data Succesfully entered");
    } else {
        toastMessage("Oopos! Something went wrong");
    }

    loadSpinnerData();

}
/*
Not useful anymore because of PillVO save function
 */

private void AddData2(String newEntry1, String newEntry2, String horario, Integer id_ppl) {

    boolean insertData = mDatabaseHelper.addData2(newEntry1, newEntry2, horario, id_ppl);
}


/*
spinner populator
 */

private void loadSpinnerData() {
    // database handler
    DatabaseHelper db = new DatabaseHelper(getApplicationContext());

    // Spinner Drop down elements
    List<String> lables = db.getAllLabels();

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

    recycler.setAdapter(new AdapterDatos(PillVO.getPills(spinner.getSelectedItem().toString())));

}

private void toastMessage(String message) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}


/*
Spinner ¿constructors?
 */

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}


public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    //first cancel discovery because its very memory intensive.
    mBluetoothAdapter.cancelDiscovery();

    Log.d(TAG, "onItemClick: You Clicked on a device.");
    String deviceName = mBTDevices.get(i).getName();
    String deviceAddress = mBTDevices.get(i).getAddress();

    Log.d(TAG, "onItemClick: deviceName = " + deviceName);
    Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

    //create the bond.
    //NOTE: Requires API 17+? I think this is JellyBean
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
        Log.d(TAG, "Trying to pair with " + deviceName);
        mBTDevices.get(i).createBond();

        mBTDevice = mBTDevices.get(i);
        mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
    }
}
}

我得到的错误是:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.example.user.project.BluetoothConnectionService.StartClient(android.bluetooth.BluetoothDevice,java.util.UUID)'

基本上,您可能需要的另一部分代码在这里:

https://github.com/mitchtabian/Sending-and-Receiving-Data-with-Bluetooth/blob/master/Bluetooth-Communication/app/src/main/java/com/example/user/bluetooth_communication/BluetoothConnectionService.java

我在这里不显示它,因为我认为它不是必需的。不是我的。

很抱歉这么简单,但是我什至不知道该如何正确地问我需要什么。但是我的想法是使用电话蓝牙接口进行连接,并使应用程序仅发送一个字符串,但是我想我通过尝试避免一些过程来弄乱了它。如果足够错,我将从头开始教程。

0 个答案:

没有答案