java.lang.NullPointerException无法启动活动

时间:2016-04-10 07:51:06

标签: android bluetooth

这是练习蓝牙基础知识的简单代码。 我在其中添加了这些功能 开启,关闭,配对设备和搜索设备。

但是,一旦我点击运行它就会显示这些错误

MainActivity.java

public class MainActivity extends Activity {

    private static final int ENABLE_BT=1;
    Button btnOn, btnOff, btnPaired, btnSearch;
    ListView listView;
    BluetoothAdapter bluetoothAdapter;
    TextView textStatus;
    Set<BluetoothDevice> bluetooDevice;
    ArrayAdapter<String> madapter;

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

        btnOn= (Button) findViewById(R.id.buttonOn);
        btnOff = (Button) findViewById(R.id.buttonOff);
        btnPaired = (Button) findViewById(R.id.buttonPaired);
        btnSearch = (Button) findViewById(R.id.buttonSearch);
        textStatus = (TextView) findViewById(R.id.textUpdateStatus);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter == null){
            btnOn.setEnabled(false);
            btnOff.setEnabled(false);
            btnPaired.setEnabled(false);
            btnSearch.setEnabled(false);
            textStatus.setText("Not Supported");
            Toast.makeText(getBaseContext(), "Your Device Does not Support Bluetooth", Toast.LENGTH_SHORT).show();
        }
        else{

            btnOn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    on(arg0);
                }


            });

            btnOff.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                }
            });


            btnPaired.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    pairedDevice(v);
                }
            });


            btnSearch.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    search(v);

                }
            });
        }

        madapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        listView.setAdapter(madapter);


    }

    public void on(View v){

        if(!bluetoothAdapter.isEnabled()){

            Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn, ENABLE_BT);
            Toast.makeText(getApplicationContext(), "Bluetooth Turned On", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Bluetooth is aleady on", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == ENABLE_BT){
            if(bluetoothAdapter.isEnabled()){
                textStatus.setText("Enabled");
            }
            else{
                textStatus.setText("Disabled");
            }
        }
    }


    public void pairedDevice(View v ){

        bluetooDevice = bluetoothAdapter.getBondedDevices();

        for(BluetoothDevice device : bluetooDevice){
            madapter.add(device.getName()+"\n"+device.getAddress());
            Toast.makeText(getApplicationContext(), "Paired Devices", Toast.LENGTH_SHORT).show();
        }
    }
    final BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();

            //when discovery finds a device
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                //Get bluetooth device object from intent

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // Add name and MAC address to adapter

                madapter.add(device.getName()+"\n"+device.getAddress());
                madapter.notifyDataSetChanged();

            }
        }

    };


    public void search(View v){

        if(bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        else{
            madapter.clear();
            bluetoothAdapter.startDiscovery();
            registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        }
    }

    public void off(View v){

        bluetoothAdapter.disable();
        textStatus.setText("Disabled");

        Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_SHORT).show();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="#112f33" >

    <Button
        android:id="@+id/buttonOn"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="44dp"
        android:layout_marginTop="148dp"
        android:text="@string/button_on"
        android:textColor="#ffffff" />

    <Button
        android:id="@+id/buttonOff"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/buttonOn"
        android:layout_alignBottom="@+id/buttonOn"
        android:layout_alignParentRight="true"
        android:layout_marginRight="36dp"
        android:text="@string/button_off" 
        android:textColor="#ffffff"/>

    <Button
        android:id="@+id/buttonPaired"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/buttonOn"
        android:layout_alignRight="@+id/buttonOff"
        android:layout_below="@+id/buttonOn"
        android:layout_marginTop="21dp"
        android:text="@string/button_paired"
        android:textColor="#ffffff" />

    <Button
        android:id="@+id/buttonSearch"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/buttonPaired"
        android:layout_alignRight="@+id/buttonPaired"
        android:layout_below="@+id/buttonPaired"
        android:layout_marginTop="28dp"
        android:text="@string/button_search"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/textStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonOff"
        android:layout_alignLeft="@+id/buttonOn"
        android:layout_marginBottom="60dp"
        android:text="@string/text_status"
        android:textColor="#ffffff"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textUpdateStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textStatus"
        android:layout_alignBottom="@+id/textStatus"
        android:layout_alignLeft="@+id/buttonOff"
         />
    <LinearLayout 
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_below="@+id/buttonSearch">

       <ListView 
        android:id="@+id/listView"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"></ListView>
       </LinearLayout>

</RelativeLayout>

logcat的

04-10 13:15:22.704: E/AndroidRuntime(439): FATAL EXCEPTION: main
04-10 13:15:22.704: E/AndroidRuntime(439): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bluetoothbasics/com.example.bluetoothbasics.MainActivity}: java.lang.NullPointerException
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.os.Looper.loop(Looper.java:123)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-10 13:15:22.704: E/AndroidRuntime(439):  at java.lang.reflect.Method.invokeNative(Native Method)
04-10 13:15:22.704: E/AndroidRuntime(439):  at java.lang.reflect.Method.invoke(Method.java:507)
04-10 13:15:22.704: E/AndroidRuntime(439):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-10 13:15:22.704: E/AndroidRuntime(439):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-10 13:15:22.704: E/AndroidRuntime(439):  at dalvik.system.NativeStart.main(Native Method)
04-10 13:15:22.704: E/AndroidRuntime(439): Caused by: java.lang.NullPointerException
04-10 13:15:22.704: E/AndroidRuntime(439):  at com.example.bluetoothbasics.MainActivity.onCreate(MainActivity.java:96)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-10 13:15:22.704: E/AndroidRuntime(439):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-10 13:15:22.704: E/AndroidRuntime(439):  ... 11 more

请帮助查找错误。谢谢。

2 个答案:

答案 0 :(得分:1)

您应该在使用之前通过findViewById初始化ListView listView;

onCreate() { ... listView = (ListView) findViewById(R.id.listView); ... }

答案 1 :(得分:0)

我无法确定因为行号丢失但我猜你在这行上有一个nullpointer因为listView为null:

listView.setAdapter(madapter);

=&GT;如果这是问题,请在设置适配器之前初始化listView。