源代码运行不报错,但是不会显示最终结果!一直是下面那个界面package com.example.a37061.myapplication;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;public class MainActivity extends AppCompatActivity {
    private Switch mBluetooh;
    private ListView listView;
    private Button aBluetooh;
    private Button search;
    private List<String> data;
    // 用来保存搜索到的设备信息
    private List<String> bluetoothDevices = new ArrayList<String>();
    // ListView的字符串数组适配器
    private ArrayAdapter<String> arrayAdapter;
    private BroadcastReceiver mReceiver;    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取蓝牙适配器
        final BluetoothAdapter adpter = BluetoothAdapter.getDefaultAdapter();
        if (adpter == null) {
            //不支持蓝牙
            Log.i("bluetooh", "该手机不支持蓝牙");
            return;
        }
        //获取界面组件
        mBluetooh = findViewById(R.id.switch1);        //为开关绑定监听器
        final BluetoothAdapter finalAdpter = adpter;
        mBluetooh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked()) {
                    // 开启switch
                    finalAdpter.enable();
                } else {
                    //关闭switch
                    finalAdpter.disable();
                }
            }
        });        //获取界面组件
        aBluetooh = findViewById(R.id.button2);
        //为开关绑定监视器
        final BluetoothAdapter finalAdpter1 = adpter;
        aBluetooh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //使本机蓝牙处于可见状态
                Intent enabler = new Intent(finalAdpter1.ACTION_REQUEST_DISCOVERABLE);
                //设置可见时间最多300秒
                enabler.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(enabler);
            }
        });        //获取界面组件
        search = findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.listView);
        IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter2);        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTitle("正在扫描...");
                // 点击搜索周边设备,如果正在搜索,则暂停搜索
                if (adpter.isDiscovering()) {
                    adpter.cancelDiscovery();
                }
                adpter.startDiscovery();
            }
            public void onDestroy() {
                //解除注册
                unregisterReceiver(mReceiver);
                Log.e("destory","解除注册");
            }
            // 注册广播接收者
            private BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent intent) {
                    // 获取到广播的action
                    String action = intent.getAction();
                    // 判断广播是搜索到设备还是搜索完成
                    if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                        // 找到设备后获取其设备
                        BluetoothDevice device = intent
                                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        // 判断这个设备是否是之前已经绑定过了,如果是则不需要添加,在程序初始化的时候已经添加了
                        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                            // 设备没有绑定过,则将其保持到arrayList集合中
                            bluetoothDevices.add(device.getName() + ":"
                                    + device.getAddress() + "\n");
                            // 更新字符串数组适配器,将内容显示在listView中
                            arrayAdapter.notifyDataSetChanged();
                        }
                    } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                        setTitle("搜索完成");
                    }
                }
            };
        });
    }
}<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">    <Button
        android:id="@+id/button"
        android:layout_width="334dp"
        android:layout_height="44dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="48dp"
        android:text="搜索蓝牙"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch1" />    <Switch
        android:id="@+id/switch1"
        android:layout_width="333dp"
        android:layout_height="34dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="蓝牙"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />    <Button
        android:id="@+id/button2"
        android:layout_width="334dp"
        android:layout_height="43dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="允许搜索"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch1" />    <TextView
        android:id="@+id/textView"
        android:layout_width="335dp"
        android:layout_height="25dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="可连接设备"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/listView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.515"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintVertical_bias="0.009" />    <ListView
        android:id="@+id/listView"
        android:layout_width="334dp"
        android:layout_height="315dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" /></android.support.constraint.ConstraintLayout>

解决方案 »

  1.   

    问题一:我没看到你的arrayAdapter在哪儿初始化的
    问题二:初始化arrayAdapter后需要设置给listView
    listView.setAdapter(arrayAdapter);
      

  2.   

    加行代码,获取到设备信息的时候给adapter添加数据                        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                                // 设备没有绑定过,则将其保持到arrayList集合中
                                bluetoothDevices.add(device.getName() + ":"
                                        + device.getAddress() + "\n");
                                arrayAdapter.add(device.getName() + ":"
                                        + device.getAddress());
                                // 更新字符串数组适配器,将内容显示在listView中
                                arrayAdapter.notifyDataSetChanged();
                            }
      

  3.   

    另外我还发现你的mReceiver这个广播也没初始化
    要不你先参考https://blog.csdn.net/qq_34536167/article/details/79432223这个看看
      

  4.   

    1楼,我加了还是不行啊@Jing丶无双 
            search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setTitle("正在扫描...");
                    adpter.startDiscovery();
                    // 注册广播接收者
                    BroadcastReceiver receiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context arg0, Intent intent) {
                            // 获取到广播的action
                            String action = intent.getAction();
                            // 判断广播是搜索到设备还是搜索完成
                            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                                // 找到设备后获取其设备
                                BluetoothDevice device = intent
                                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                setTitle("+1");
                                // 判断这个设备是否是之前已经绑定过了,如果是则不需要添加,在程序初始化的时候已经添加了
                                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                                    // 设备没有绑定过,则将其保持到arrayList集合中
                                    setTitle("+2");
                                    ArrayAdapter<String> qdapter=new ArrayAdapter<String>(MainActivity.this, simple_expandable_list_item_1,getData());
                                    listView.setAdapter(qdapter);
                                    // 更新字符串数组适配器,将内容显示在listView中
                                    setContentView(listView);
                                }
                            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                                setTitle("搜索完成");
                            }
                        }
                    };
                }
                public void onDestroy() {
                    //解除注册
                    unregisterReceiver(mReceiver);
                    Log.e("destory","解除注册");
                }
            });
        }    public List<String> getData() {
            List<String> data = new ArrayList<String>();
            Intent intent = null;
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            bluetoothDevices.add(device.getName() + ":"
                    + device.getAddress() + "\n");
            data.add(device.getName() + ":"
                    + device.getAddress());
            return data;
        }
    }
      

  5.   

    4楼也是我回答的啊,我发现你代码问题挺多的,给你提供了这个参考链接https://blog.csdn.net/qq_34536167/article/details/79432223
      

  6.   

    我参考了一下,但是设置了列表适配器以后,程序在手机上运行会闪退,是为什么?@Jing丶无双 
      

  7.   

    这是手机调试时报的错误
    E/AndroidRuntime: FATAL EXCEPTION: main
                      Process: com.example.a37061.myapplication, PID: 21030
                      java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.example.a37061.myapplication.MainActivity$4@6cfee8
                          at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:965)
                          at android.os.Handler.handleCallback(Handler.java:815)
                          at android.os.Handler.dispatchMessage(Handler.java:104)
                          at android.os.Looper.loop(Looper.java:194)
                          at android.app.ActivityThread.main(ActivityThread.java:5898)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814)
                       Caused by: java.lang.ClassCastException: com.example.a37061.myapplication.MyAdapter cannot be cast to android.widget.ListAdapter
                          at com.example.a37061.myapplication.MainActivity$4.onReceive(MainActivity.java:136)
                          at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:953)
                          at android.os.Handler.handleCallback(Handler.java:815) 
                          at android.os.Handler.dispatchMessage(Handler.java:104) 
                          at android.os.Looper.loop(Looper.java:194) 
                          at android.app.ActivityThread.main(ActivityThread.java:5898) 
                          at java.lang.reflect.Method.invoke(Native Method) 
                          at java.lang.reflect.Method.invoke(Method.java:372) 
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019) 
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814) 
      

  8.   

    Caused by: java.lang.ClassCastException: com.example.a37061.myapplication.MyAdapter cannot be 
    cast to android.widget.ListAdapter
    at com.example.a37061.myapplication.MainActivity$4.onReceive(MainActivity.java:136)错误是在你的MainActivity的第136行,MyAdapter不能强转换为ListAdapter,看看你自己怎么赋值的
      

  9.   

    而且搜不到HC-06这个设备!@Jing丶无双
      

  10.   

    package com.example.a37061.myapplication;import android.bluetooth.BluetoothDevice;
    import android.content.Context;
    import android.database.DataSetObserver;
    import android.text.TextUtils;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ListAdapter;
    import android.widget.TextView;import java.util.List;public class MyAdapter implements ListAdapter {    private List<BluetoothDevice> mBluelist;
        private LayoutInflater layoutInflater;    public MyAdapter(MainActivity context, List<BluetoothDevice> list) {
            this.mBluelist = list;
            this.layoutInflater = LayoutInflater.from(context);
        }    @Override
        public boolean areAllItemsEnabled() {
            return false;
        }    @Override
        public boolean isEnabled(int position) {
            return false;
        }    @Override
        public void registerDataSetObserver(DataSetObserver observer) {    }    @Override
        public void unregisterDataSetObserver(DataSetObserver observer) {    }    @Override
        public int getCount() {
            return mBluelist.size();
        }    @Override
        public Object getItem(int position) {
            return mBluelist.get(position);
        }    @Override
        public long getItemId(int position) {
            return position;
        }    @Override
        public boolean hasStableIds() {
            return false;
        }    @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = layoutInflater.inflate(R.layout.list_device_item, null);
                viewHolder.deviceName = view.findViewById(R.id.device_name);
                viewHolder.deviceAddress = view.findViewById(R.id.device_address);
                viewHolder.deviceType = view.findViewById(R.id.device_type);
                viewHolder.deviceState = view.findViewById(R.id.device_state);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            //详细参考:http://blog.csdn.net/mirkowu/article/details/53862842
            BluetoothDevice blueDevice = mBluelist.get(position);
            //设备名称
            String deviceName = blueDevice.getName();
            viewHolder.deviceName.setText(TextUtils.isEmpty(deviceName) ? "未知设备" : deviceName);
            //设备的蓝牙地(地址为17位,都为大写字母-该项貌似不可能为空)
            String deviceAddress = blueDevice.getAddress();
            viewHolder.deviceAddress.setText(deviceAddress);
            //设备的蓝牙设备类型(DEVICE_TYPE_CLASSIC 传统蓝牙 常量值:1, DEVICE_TYPE_LE  低功耗蓝牙 常量值:2
            //DEVICE_TYPE_DUAL 双模蓝牙 常量值:3. DEVICE_TYPE_UNKNOWN:未知 常量值:0)
            int deviceType = blueDevice.getType();
            if (deviceType == 0) {
                viewHolder.deviceType.setText("未知类型");
            } else if (deviceType == 1) {
                viewHolder.deviceType.setText("传统蓝牙");
            } else if (deviceType == 2) {
                viewHolder.deviceType.setText("低功耗蓝牙");
            } else if (deviceType == 3) {
                viewHolder.deviceType.setText("双模蓝牙");
            }
            //设备的状态(BOND_BONDED:已绑定 常量值:12, BOND_BONDING:绑定中 常量值:11, BOND_NONE:未匹配 常量值:10)
            int deviceState = blueDevice.getBondState();
            if (deviceState == 10) {
                viewHolder.deviceState.setText("未匹配");
            } else if (deviceState == 11) {
                viewHolder.deviceState.setText("绑定中");
            } else if (deviceState == 12) {
                viewHolder.deviceState.setText("已绑定");
            }
            //返回远程设备支持的UUID。此方法从远程设备检索UUID不启动服务。 而是返回服务UUID的本地缓存。
            //如果需要刷新UUID,使用fetchUuidsWithSdp()方法
            //ParcelUuid[] deviceUuid = blueDevice.getUuids();
            //blueDevice.fetchUuidsWithSdp(); boolean类型
            return view;
        }    private class ViewHolder {
            TextView deviceName;
            TextView deviceAddress;
            TextView deviceType;
            TextView deviceState;
        }    @Override
        public int getItemViewType(int position) {
            return 0;
        }    @Override
        public int getViewTypeCount() {
            return 0;
        }    @Override
        public boolean isEmpty() {
            return false;
        }
    }手机调试时提示java.lang.IllegalArgumentException: Can't have a viewTypeCount 
    但是我如果删掉它就提示未覆盖
      

  11.   

    那你先完全用这个链接https://blog.csdn.net/qq_34536167/article/details/79432223里面的代码看能不能搜索到你的蓝牙设备呢,如果可以的话,你再在上面进行修改,改成你想实现的效果
      

  12.   

    已经解决了 viewTypeCount ,把返回值改成0就没问题了,我现在要做点击链接的内容,我找了一些别人写的有点看不懂,你有什么可以推荐博客吗,注释清楚一点最好,我现在按照到的好像做不出来。@Jing丶无双 
      

  13.   

    已经解决了 viewTypeCount ,把返回值改成1就没问题了,我现在要做点击链接的内容,我找了一些别人写的有点看不懂,你有什么可以推荐博客吗,注释清楚一点最好,我现在按照到的好像做不出来。@Jing丶无双 
      

  14.   

    https://blog.csdn.net/a1533588867/article/details/52442349
    这个博客分了三篇写,还是相对清晰,你先看看,试着做做
      

  15.   

    我现在的程序是:
    package com.example.a37061.myapplication;import android.annotation.SuppressLint;
    import android.app.ProgressDialog;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.CompoundButton;
    import android.widget.ListView;
    import android.widget.Switch;
    import android.widget.TextView;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    public class MainActivity extends AppCompatActivity {
        private Switch mBluetooh = findViewById(R.id.switch1);
        private Button aBluetooh = findViewById(R.id.button2);
        private Button search = findViewById(R.id.button);
        private TextView humidity = findViewById(R.id.textView5);
        private Button button = findViewById(R.id.button3);
        private ListView listView = findViewById(R.id.listView);;
        private TextView textView1 = findViewById(R.id.textView1);;    private BluetoothAdapter adpter = BluetoothAdapter.getDefaultAdapter();
        private static final String TAG = "MainActivity";
        private List<BluetoothDevice> mBlueList = new ArrayList<>();
        private final static int SEARCH_CODE = 0x123;
        private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //获取蓝牙适配器
            if (adpter == null) {
                //不支持蓝牙
                Log.i("bluetooh", "该手机不支持蓝牙");
                setTitle("该手机不支持蓝牙");
                return;
            }        //为开关绑定监听器
            final BluetoothAdapter finalAdpter = adpter;
            mBluetooh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (compoundButton.isChecked()) {
                        // 开启switch
                        finalAdpter.enable();
                        setTitle("蓝牙已经打开");
                    } else {
                        //关闭switch
                        finalAdpter.disable();
                        setTitle("蓝牙已经关闭");
                    }
                }
            });        //为开关绑定监视器
            aBluetooh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //使本机蓝牙处于可见状态
                    Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    //设置可见时间最多300秒
                    enabler.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    startActivity(enabler);
                }
            });        search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startDiscovery();
                }
            });
        }    private void startDiscovery() {
            // 找到设备的广播
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            // 注册广播
            registerReceiver(receiver, filter);
            // 搜索完成的广播
            IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            // 注册广播
            registerReceiver(receiver, filter1);
            Log.e(TAG, "startDiscovery: 注册广播");
            startScanBluth();
        }    private final BroadcastReceiver receiver = new BroadcastReceiver() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onReceive(Context context, Intent intent) {
                // 收到的广播类型
                String action = intent.getAction();
                // 发现设备的广播
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // 从intent中获取设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // 没否配对
                    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                        if (!mBlueList.contains(device)) {
                            mBlueList.add(device);
                        }
                        textView1.setText("附近设备:" + mBlueList.size() + "个\u3000\u3000本机蓝牙地址:" + getBluetoothAddress());
                        MyAdapter adapter = new MyAdapter(MainActivity.this, mBlueList);
                        listView.setAdapter(adapter);                    Log.e(TAG, "onReceive: " + mBlueList.size());
                        Log.e(TAG, "onReceive: " + (device.getName() + ":" + device.getAddress() + " :" + "m" + "\n"));
                    }
                    // 搜索完成
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    // 关闭进度条
                    progressDialog.dismiss();
                    Log.e(TAG, "onReceive: 搜索完成");
                }
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (adpter.isDiscovering()) {
                            adpter.cancelDiscovery();
                        }
                        MyAdapter adapter = new MyAdapter(MainActivity.this, mBlueList);
                        BluetoothDevice device = (BluetoothDevice) adapter.getItem(position);
                        connectDevice(device);
                    }
                });
            }
        };    private void connectDevice(BluetoothDevice device) {
            try {
                //创建Socket
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
                //启动连接线程
                socket.connect();
                InputStream inputStream = socket.getInputStream();
                final OutputStream outputStream = socket.getOutputStream();
                byte[] buffer = new byte[256];
                int bytes;
                while (true) {
                    //读取数据
                    bytes = inputStream.read(buffer);
                    if (bytes > 0) {
                        final byte[] data = new byte[bytes];
                        System.arraycopy(buffer, 0, data, 0, bytes);
                        humidity.post(new Runnable() {
                            @Override
                            public void run() {
                                humidity.setText(new String(data));
                            }
                        });
                    }
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int bytes = 1;
                            try {
                                outputStream.write(bytes);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }    private ProgressDialog progressDialog;    private void startScanBluth() {
            // 判断是否在搜索,如果在搜索,就取消搜索
            if (adpter.isDiscovering()) {
                adpter.cancelDiscovery();
            }
            // 开始搜索
            adpter.startDiscovery();
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            progressDialog.setMessage("正在搜索,请稍后!");
            progressDialog.show();
        }    @Override
        protected void onDestroy() {
            super.onDestroy();
            //取消注册,防止内存泄露(onDestroy被回调代不代表Activity被回收?:具体回收看系统,由GC回收,同时广播会注册到系统
            //管理的ams中,即使activity被回收,reciver也不会被回收,所以一定要取消注册),
            unregisterReceiver(receiver);
        }    private String getBluetoothAddress() {
            try {
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
                // 参数值为true,禁用访问控制检查
                field.setAccessible(true);
                Object bluetoothManagerService = field.get(bluetoothAdapter);
                if (bluetoothManagerService == null) {
                    return null;
                }
                Method method = bluetoothManagerService.getClass().getMethod("getAddress");
                Object address = method.invoke(bluetoothManagerService);
                if (address != null && address instanceof String) {
                    return (String) address;
                } else {
                    return null;
                }
                //抛一个总异常省的一堆代码...
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode==SEARCH_CODE){
                startDiscovery();
            }
            Log.e(TAG, "onActivityResult: "+requestCode );
            Log.e(TAG, "onActivityResult: "+resultCode );
            Log.e(TAG, "onActivityResult: "+requestCode );
        }
    }
      

  16.   

    他会报下面的错误,是怎么回事?@Jing丶无双 
    E/AndroidRuntime: FATAL EXCEPTION: main
                      Process: com.example.a37061.myapplication, PID: 32502
                      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.a37061.myapplication/com.example.a37061.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                          at android.app.ActivityThread.access$900(ActivityThread.java:187)
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
                          at android.os.Handler.dispatchMessage(Handler.java:111)
                          at android.os.Looper.loop(Looper.java:194)
                          at android.app.ActivityThread.main(ActivityThread.java:5898)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814)
                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                          at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
                          at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
                          at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:56)
                          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
                          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                          at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                          at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                          at com.example.a37061.myapplication.MainActivity.<init>(MainActivity.java:35)
                          at java.lang.reflect.Constructor.newInstance(Native Method)
                          at java.lang.Class.newInstance(Class.java:1650)
                          at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2586)
                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754) 
                          at android.app.ActivityThread.access$900(ActivityThread.java:187) 
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584) 
                          at android.os.Handler.dispatchMessage(Handler.java:111) 
                          at android.os.Looper.loop(Looper.java:194) 
                          at android.app.ActivityThread.main(ActivityThread.java:5898) 
                          at java.lang.reflect.Method.invoke(Native Method) 
                          at java.lang.reflect.Method.invoke(Method.java:372) 
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019) 
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814)
      

  17.   

    首先你得自己学会看报错,一般报错主要看两个位置:
    1.报错最顶部的信息:
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.a37061.myapplication/com.example.a37061.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
    这里的报错是说RuntimeException运行错误在com.example.a37061.myapplication包里的MainActivity中产生了NullPointerException空指针异常2.报错包含Caused by以下的信息:
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                          at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
                          at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
                          at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:56)
                          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
                          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                          at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                          at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                          at com.example.a37061.myapplication.MainActivity.<init>(MainActivity.java:35)
    Caused by以下的信息这最后一句就提示的很明显了MainActivity.java:35MainActivity第35行报错综上所述:
    看看你的代码35行到41行
    private Switch mBluetooh = findViewById(R.id.switch1);
        private Button aBluetooh = findViewById(R.id.button2);
        private Button search = findViewById(R.id.button);
        private TextView humidity = findViewById(R.id.textView5);
        private Button button = findViewById(R.id.button3);
        private ListView listView = findViewById(R.id.listView);;
        private TextView textView1 = findViewById(R.id.textView1);布局都没有加载,你就开始findViewById能不报空指针异常么,我们都是从布局里面找相应控件的。所以给这些控件初始化话的时候一定要在布局加载之后,那么这里应该这么写,而且你得确保你的activity_main布局中是存在这些相应控件的    private Switch mBluetooh ;
        private Button aBluetooh ;
        private Button search ;
        private TextView humidity ;
        private Button button ;
        private ListView listView ;
        private TextView textView1;


    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        mBluetooh = findViewById(R.id.switch1);
            aBluetooh = findViewById(R.id.button2);
    search = findViewById(R.id.button);
    humidity = findViewById(R.id.textView5);
    button = findViewById(R.id.button3);
    listView = findViewById(R.id.listView);;
    textView1 = findViewById(R.id.textView1);

    }
      

  18.   

    肯定不是这里报错了...再贴日志.....然后你findviewbyid都不强制类型转换都不报错么....
      

  19.   


    05/17 10:32:45: Launching app
    $ adb install-multiple -r -t -p com.example.a37061.myapplication D:\file\SKS\app\build\intermediates\split-apk\debug\slices\slice_9.apk D:\file\SKS\app\build\intermediates\instant-run-apk\debug\app-debug.apk 
    Split APKs installed
    $ adb shell am start -n "com.example.a37061.myapplication/com.example.a37061.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
    Connected to process 17621 on device meizu-mx5-85GABM8FAX62
    Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
    W/Zygote: mz_is_rooted false
    I/art: Late-enabling -Xcheck:jni
    E/System: stat file error, path is /data/app/com.example.a37061.myapplication-2/lib/arm64, exception is android.system.ErrnoException: stat failed: ENOENT (No such file or directory)
    W/linker: /system/lib64/libfilterUtils.so: unused DT entry: type 0x6ffffffe arg 0x808
              /system/lib64/libfilterUtils.so: unused DT entry: type 0x6fffffff arg 0x2
    I/InstantRun: starting instant run server: is main process
    W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
    E/AndroidRuntime: FATAL EXCEPTION: main
                      Process: com.example.a37061.myapplication, PID: 17621
                      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a37061.myapplication/com.example.a37061.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2685)
                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
                          at android.app.ActivityThread.access$900(ActivityThread.java:187)
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
                          at android.os.Handler.dispatchMessage(Handler.java:111)
                          at android.os.Looper.loop(Looper.java:194)
                          at android.app.ActivityThread.main(ActivityThread.java:5898)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814)
                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
                          at com.example.a37061.myapplication.MainActivity.onCreate(MainActivity.java:65)
                          at android.app.Activity.performCreate(Activity.java:6127)
                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2638)
                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754) 
                          at android.app.ActivityThread.access$900(ActivityThread.java:187) 
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584) 
                          at android.os.Handler.dispatchMessage(Handler.java:111) 
                          at android.os.Looper.loop(Looper.java:194) 
                          at android.app.ActivityThread.main(ActivityThread.java:5898) 
                          at java.lang.reflect.Method.invoke(Native Method) 
                          at java.lang.reflect.Method.invoke(Method.java:372) 
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1019) 
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:814) 
    I/Process: Sending signal. PID: 17621 SIG: 9
    Application terminated.
    这是所有的了
    public class MainActivity extends AppCompatActivity {
        private TextView humidity;
        private Button button;
        private ListView listView;
        private TextView textView1;    private BluetoothAdapter adpter = BluetoothAdapter.getDefaultAdapter();
        private static final String TAG = "MainActivity";
        private List<BluetoothDevice> mBlueList = new ArrayList<>();
        private final static int SEARCH_CODE = 0x123;
        private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Switch bswitch = findViewById(R.id.switch1);
            Button Bbutton = findViewById(R.id.button2);
            Button search = findViewById(R.id.button);
            humidity = findViewById(R.id.textView5);
            button = findViewById(R.id.button3);
            listView = findViewById(R.id.listView);
            textView1 = findViewById(R.id.textView1);
            setContentView(R.layout.activity_main);
      

  20.   

    package com.example.a37061.myapplication;
    import android.annotation.SuppressLint;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.app.ProgressDialog;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.CompoundButton;
    import android.widget.ListView;
    import android.widget.Switch;
    import android.widget.TextView;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    public class MainActivity extends AppCompatActivity {
        private TextView humidity;
        private Button button;
        private ListView listView;
        private TextView textView1;    private BluetoothAdapter adpter = BluetoothAdapter.getDefaultAdapter();
        private static final String TAG = "MainActivity";
        private List<BluetoothDevice> mBlueList = new ArrayList<>();
        private final static int SEARCH_CODE = 0x123;
        private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Switch bswitch = findViewById(R.id.switch1);
            Button Bbutton = findViewById(R.id.button2);
            Button search = findViewById(R.id.button);
            humidity = findViewById(R.id.textView5);
            button = findViewById(R.id.button3);
            listView = findViewById(R.id.listView);
            textView1 = findViewById(R.id.textView1);
            setContentView(R.layout.activity_main);        if (adpter == null) {
                //不支持蓝牙
                Log.i("bluetooh", "该手机不支持蓝牙");
                setTitle("该手机不支持蓝牙");
                return;
            }        //为开关绑定监听器
            bswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean b) {
                    if (b) {
                        // 开启switch
                        adpter.enable();
                        setTitle("蓝牙已经打开");
                    } else {
                        //关闭switch
                        adpter.disable();
                        setTitle("蓝牙已经关闭");
                    }
                }
            });
      

  21.   

    在我写连接和数据交互的这段程序前都能用,但是写完以后,switch就开始报空指针了
      

  22.   

    你switch对象为空啊,查查看你的XML是否有这个ID的swich控件,提示你无法setOnCheckedChangeListener在一个空对象上
      

  23.   

    找到错误了,findByID要放在set后面
      

  24.   

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        MyAdapter adapter = new MyAdapter(MainActivity.this, mBlueList);
                        BluetoothDevice device = (BluetoothDevice) adapter.getItem(position);
                        connectDevice(device);
                    }
                });
    点击列表项以后怎么没用
      

  25.   

    @Jing丶无双