获得蓝牙设备

时间:2014-08-28 11:29:25

标签: android bluetooth

我正在搜索Google,并在stackoverflow中找到了一个代码。我开始使用它,但行list.setAdapter(aa);正在生成NullPointerException。我该如何解决?这是我的MainActivity.java

public class MainActivity extends Activity {
    private static int DISCOVERY_REQUEST = 1;

    private Handler handler = new Handler();
    private ArrayList<BluetoothDevice> foundDevices;
    private ArrayAdapter<BluetoothDevice> aa;
    private ListView list;

    private BluetoothAdapter bluetooth;
    private BluetoothSocket socket;
    private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");

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

        configureBluetooth();
        setupListView();
        setupSearchButton();
        setupListenButton();
    }

    private void configureBluetooth() {
        bluetooth = BluetoothAdapter.getDefaultAdapter();
    }

    private void setupListenButton() {
        Button listenButton = (Button) findViewById(R.id.button_listen);
        listenButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                Intent disc = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(disc, DISCOVERY_REQUEST);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == DISCOVERY_REQUEST) {
            boolean isDiscoverable = resultCode > 0;
            if (isDiscoverable) {
                String name = "bluetoothserver";
                try {
                    final BluetoothServerSocket btserver = bluetooth
                            .listenUsingRfcommWithServiceRecord(name, uuid);

                    AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>() {

                        @Override
                        protected BluetoothSocket doInBackground(
                                Integer... params) {
                            try {
                                socket = btserver.accept(params[0] * 1000);
                                return socket;
                            } catch (IOException e) {
                                Log.d("BLUETOOTH", e.getMessage());
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(BluetoothSocket result) {
                            if (result != null)
                                switchUI();
                        }
                    };
                    acceptThread.execute(resultCode);
                } catch (IOException e) {
                    Log.d("BLUETOOTH", e.getMessage());
                }
            }
        }
    }

    private void setupListView() {
        aa = new ArrayAdapter<BluetoothDevice>(this,
                android.R.layout.simple_list_item_1, foundDevices);
        list = (ListView) findViewById(R.id.list_discovered);
        list.setAdapter(aa); //the error comes from this line

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int index,
                    long arg3) {
                AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
                    @Override
                    protected Void doInBackground(Integer... params) {
                        try {
                            BluetoothDevice device = foundDevices
                                    .get(params[0]);
                            socket = device
                                    .createRfcommSocketToServiceRecord(uuid);
                            socket.connect();
                        } catch (IOException e) {
                            Log.d("BLUETOOTH_CLIENT", e.getMessage());
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        switchUI();
                    }
                };
                connectTask.execute(index);
            }
        });
    }

    private void setupSearchButton() {
        Button searchButton = (Button) findViewById(R.id.button_search);

        searchButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                registerReceiver(discoveryResult, new IntentFilter(
                        BluetoothDevice.ACTION_FOUND));

                if (!bluetooth.isDiscovering()) {
                    foundDevices.clear();
                    bluetooth.startDiscovery();
                }
            }
        });
    }

    private void switchUI() {
        final TextView messageText = (TextView) findViewById(R.id.text_messages);
        final EditText textEntry = (EditText) findViewById(R.id.text_message);

        messageText.setVisibility(View.VISIBLE);
        list.setVisibility(View.GONE);
        textEntry.setEnabled(true);

        textEntry.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
                    sendMessage(socket, textEntry.getText().toString());
                    textEntry.setText("");
                    return true;
                }
                return false;
            }
        });
        BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
                handler, messageText);
        Thread messageListener = new Thread(bsl);
        messageListener.start();
    }

    private void sendMessage(BluetoothSocket socket, String msg) {
        OutputStream outStream;
        try {
            outStream = socket.getOutputStream();
            byte[] byteString = (msg + " ").getBytes();
            byteString[byteString.length - 1] = 0;
            outStream.write(byteString);
        } catch (IOException e) {
            Log.d("BLUETOOTH_COMMS", e.getMessage());
        }
    }

    BroadcastReceiver discoveryResult = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice remoteDevice;
            remoteDevice = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (bluetooth.getBondedDevices().contains(remoteDevice)) {
                foundDevices.add(remoteDevice);
                aa.notifyDataSetChanged();
            }
        }
    };

    private class MessagePoster implements Runnable {
        private TextView textView;
        private String message;

        public MessagePoster(TextView textView, String message) {
            this.textView = textView;
            this.message = message;
        }

        public void run() {
            textView.setText(message);
        }
    }

    private class BluetoothSocketListener implements Runnable {

        private BluetoothSocket socket;
        private TextView textView;
        private Handler handler;

        public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
                TextView textView) {
            this.socket = socket;
            this.textView = textView;
            this.handler = handler;
        }

        public void run() {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            try {
                InputStream instream = socket.getInputStream();
                int bytesRead = -1;
                String message = "";
                while (true) {
                    message = "";
                    bytesRead = instream.read(buffer);
                    if (bytesRead != -1) {
                        while ((bytesRead == bufferSize)
                                && (buffer[bufferSize - 1] != 0)) {
                            message = message
                                    + new String(buffer, 0, bytesRead);
                            bytesRead = instream.read(buffer);
                        }
                        message = message
                                + new String(buffer, 0, bytesRead - 1);

                        handler.post(new MessagePoster(textView, message));
                        socket.getInputStream();
                    }
                }
            } catch (IOException e) {
                Log.d("BLUETOOTH_COMMS", e.getMessage());
            }
        }
    }

}

错误是:

Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:464)
at com.example.testbluetooth.MainActivity.setupListView(MainActivity.java:113)

这是我的activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/text_message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:enabled="false" />

    <Button
        android:id="@+id/button_search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/text_message"
        android:text="Search for listener" />

    <Button
        android:id="@+id/button_listen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/button_search"
        android:text="Listen for connection" />

    <ListView
        android:id="@+id/list_discovered"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/button_listen"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/text_messages"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/button_listen"
        android:layout_alignParentTop="true"
        android:visibility="gone" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

您有空列表,在设置列表之前设置数组列表。

尝试删除

来自setupListView()

onCreate()

并在创建设备列表后将其放置到位。

你可以尝试这样做:

  1. 在您的情况下初始化集合只需写private ArrayList<BluetoothDevice> foundDevices = new ArrayList<BluetoothDevice>();
  2. 当您收到广播时foundDevices.add(remoteDevice);
  3. aa.addAll(foundDevices)然后致电aa.notifyDataSetChanged();
  4. 参考文献: ArrayAdapter.AddAll()