我正在使用arduino uno和HC-05蓝牙模块创建一个家庭自动化android应用程序。一切都很好。它可以扫描,连接,打开/关闭蓝牙,使用按钮和开关控制来控制灯泡的打开和关闭,但是应用程序的设计很糟糕。因此,我决定使用Tab窗口小部件。问题是,当我更改某些内容时,它将无法运行并显示NullPointerException问题,并且我不知道为什么ots会发生,因为它在过去的几天中已经可以正常工作了。

以下是LogCat中的列表:

02-21 08:48:18.063: E/AndroidRuntime(25982): FATAL EXCEPTION: main
02-21 08:48:18.063: E/AndroidRuntime(25982): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.ControllerTab}: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.os.Handler.dispatchMessage(Handler.java:107)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.os.Looper.loop(Looper.java:194)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.main(ActivityThread.java:5371)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at java.lang.reflect.Method.invokeNative(Native Method)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at java.lang.reflect.Method.invoke(Method.java:525)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at dalvik.system.NativeStart.main(Native Method)
02-21 08:48:18.063: E/AndroidRuntime(25982): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.ControllerTab}: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:2186)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost.setCurrentTab(TabHost.java:413)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost.addTab(TabHost.java:240)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.example.javac101.MainActivity.onCreate(MainActivity.java:164)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Activity.performCreate(Activity.java:5122)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-21 08:48:18.063: E/AndroidRuntime(25982):    ... 11 more
02-21 08:48:18.063: E/AndroidRuntime(25982): Caused by: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.example.javac101.ControllerTab.onCreate(ControllerTab.java:110)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Activity.performCreate(Activity.java:5122)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-21 08:48:18.063: E/AndroidRuntime(25982):    ... 21 more


我的MainActivity中的Logcat中提到的行:

tabHost.addTab(tabSpecController);


我的ControllerTab中Logcat中提到的行:

list.setOnItemClickListener(new OnItemClickListener()


可能不清楚,所以这是我在MainActivity中的代码:
包com.example.javac101;

public class MainActivity extends TabActivity {

    //BLUETOOTH
        BluetoothAdapter            BTAdapter;
        //BluetoothDevice               BTDevice;

    //Layout view daw
        public static TextView title;
        public static ImageView status;

    //Intent
        private static final int    REQUEST_DEVICE_CONNECT = 1;
        private static final int    REQUEST_ENABLE_BLUETOOTH = 2;
        private static final int    REQUEST_ABOUTS = 3;


        //object for bluetooth command service
        public static BluetoothCommandService commandService = null;


        //
        private String connectedDeviceName = null;

        //Message types sent from the Handler
        public static final int MESSAGE_STATE_CHANGE = 1;
        public static final int MESSAGE_READ = 2;
        public static final int MESSAGE_WRITE = 3;
        public static final int MESSAGE_DEVICE_NAME = 4;
        public static final int MESSAGE_TOAST = 5;
        public static final int RECIEVE_MESSAGE = 6;



        //Will be used in BluetoothCommandSrvice jave file
        public static final String TOAST = "toast";
        public static final String DEVICENAME = "device name";


        public static final String HC05 = "20:13:06:19:34:54";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
        if (address.equals(MainActivity.HC05))
        {
            Intent login = new Intent (this, LoginActivity.class);
        }
        else
        {
            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
            setContentView(R.layout.tabs);

            /**
             * DATABASE CRUD Operations
             * */

            DatabaseHandler db = new DatabaseHandler(this);

            // Inserting Devices
            Log.d("Insert: ", "Inserting ..");
            db.addDevice(new Device(1, "DB Device 1"));
            db.addDevice(new Device(2, "DB Device 2"));
            db.addDevice(new Device(3, "DB Device 3"));

        // Reading all devices
            Log.d("Reading: ", "Reading all devices..");
            List<Device> devices = db.getAllDevices();

            for (Device dv : devices) {
                String log = "Id: "+dv.getID()+" ,Name: " + dv.getName();
                Log.d("Name: ", log);
            }


            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
                title = (TextView) findViewById(R.id.title_left_text);  // Set up the custom title
                title.setText(R.string.app_name);                       // Set up the custom title
                title = (TextView) findViewById(R.id.title_right_text); // Set up the custom title
Resources ressources = getResources();
            TabHost tabHost2 = getTabHost();
            TabHost tabHost = tabHost2;

            // Controller Tab
            Intent intentController = new Intent().setClass(this, ControllerTab.class);
            TabSpec tabSpecController = tabHost
                    .newTabSpec("Controller")
                    .setIndicator("", ressources.getDrawable(R.drawable.icon_home_config))
                    .setContent(intentController);

            // Setting Tab
                    Intent intentSetting = new Intent().setClass(this, Settings.class);
                    TabSpec tabSpecSetting = tabHost
                      .newTabSpec("Setting")
                      .setIndicator("", ressources.getDrawable(R.drawable.icon_settings_config))
                      .setContent(intentSetting);


            // add all tabs
            tabHost.addTab(tabSpecController);
            tabHost.addTab(tabSpecSetting);

            //set Windows tab as default (zero based)
            tabHost.setCurrentTab(0);
// AUTO REQUEST OF ENABLING THE BLUETOOTH
            BTAdapter = BluetoothAdapter.getDefaultAdapter();

            //A code that will detect if BT is enabled otherwise will require it.
            if (BTAdapter == null)
            {
                //Toast.makeText(context, text, duration)
                Toast.makeText(this, "No Bluetooth adapter is available.", Toast.LENGTH_LONG).show();
                finish();
                return;
            }


        }
    }



    private void setVisible(int tabs, boolean b) {
        // TODO Auto-generated method stub

    }



    @Override
    protected void onStart()
    {
        super.onStart();
        //Requesting Bluetooth automatically when its not yet enabled.
        if (!BTAdapter.isEnabled())
        {
            Intent enableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //startActivityForResult(enableIntent, 0);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
        }
        else
        {
            if (commandService == null)
                setupCommand();
        }
    }
@Override
    protected void onResume() {
        super.onResume();

        if (commandService != null)
        {
            if (commandService.getState() == BluetoothCommandService.stateNothing)
            {
                commandService.start();
            }
        }
    }

    private void setupCommand()
    {
        commandService = new BluetoothCommandService(this, bluetoothHandler);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (commandService != null)
            commandService.stop();
    }
public final Handler bluetoothHandler = new Handler()
        {
            @Override
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                    case MESSAGE_STATE_CHANGE:
                        switch (msg.arg1)
                        {
                            case BluetoothCommandService.stateConnected:
                                title.setText(R.string.title_connectedTo);
                                title.append(connectedDeviceName);
                                break;

                            case BluetoothCommandService.stateConnecting:
                                title.setText(R.string.title_connecting);
                                break;

                            case BluetoothCommandService.stateListen:
                            case BluetoothCommandService.stateNothing:
                                title.setText(getString(R.string.title_notConnected));
                                break;
                        }
                        break;

                    case MESSAGE_DEVICE_NAME:
                        connectedDeviceName = msg.getData().getString(DEVICENAME);
                        Toast.makeText(getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT).show();
                        break;

                    case MESSAGE_TOAST:
                        Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                        break;

                    //case RECIEVE_MESSAGE:                                                 // if receive message
                    //  byte[] readBuf = (byte[]) msg.obj;
                    //  String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                    //  sb.append(strIncom);                                                // append string
                    //  int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                    //  if (endOfLineIndex > 0) {                                           // if end-of-line,
                    //      //String sbprint = sb.substring(0, endOfLineIndex);             // extract string
                    //        sb.delete(0, sb.length());                                        // and clear
                            //txtArduino.setText("Data from Arduino: " + sbprint);          // update TextView
                            //1/4/14
                    //      btn_d1_on.setEnabled(true);
                    //  btn_d1_off.setEnabled(true);
                        //   }
                        //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                        //break;

                }
                //return false;
            }
        };
        //});

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
            case REQUEST_DEVICE_CONNECT:
                // When DeviceList Activity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    //String address = data.getExtras().getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                    String address = new String(data.getExtras().getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS));
                        if (address.equals(HC05))
                        {
                            // Get the BLuetoothDevice object
                            BluetoothDevice device = BTAdapter.getRemoteDevice(address);
                            // Attempt to connect to the device
                            commandService.connect(device);
                        }
                        else
                        {
                            Toast.makeText(this, "This device is not for JavaC101 Application. Please connect to HC-05 device.", Toast.LENGTH_LONG).show();
                        }
                }
                break;

            case REQUEST_ENABLE_BLUETOOTH:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupCommand();
                } else {
                   // User did not enable Bluetooth or an error occured
                    Toast.makeText(this, R.string.notEnabledBluetooth, Toast.LENGTH_SHORT).show();
                    finish();
               }


            }
        }
@Override
    //Creating an Option Menu for connectivity and discoverability of a BT device
    public boolean onCreateOptionsMenu(Menu menu)
    {
        //MenuInflater is a class
        MenuInflater OptionMenu = getMenuInflater();
        //OptionMenu.inflate(menuRes, menu)
        OptionMenu.inflate(R.menu.main, menu);
        return true;
    }




    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.connect:
                connect();
                return true;
            case R.id.bton:
                bluetoothOn();
                return true;
            case R.id.btoff:
                bluetoothOff();
                return true;
            case R.id.abouts:
                abouts();
                return true;
            //default:
                //return super.onOptionsItemSelected(item);
        }
        return false;
    }

    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

      private void connect()
      {
          Intent serverIntent = new Intent(this, DeviceList.class);
          this.startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
          //startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
      }

      private void bluetoothOn()
      {
          BTAdapter.enable();
          Toast.makeText(this, "Bluetooth is now turned on", Toast.LENGTH_SHORT).show();
      }

      private void bluetoothOff()
      {
          BTAdapter.disable();
          Toast.makeText(this, "Bluetooth is now turned off.", Toast.LENGTH_SHORT).show();
      }

      private void abouts()
      {
          Intent intentAbouts = new Intent(this, abouts.class);
          //startActivityForResult(intentAbouts, REQUEST_ABOUTS);
          startActivity(intentAbouts);
      }


由于我的另一个类ControllerTab中也存在错误,因此这是我的代码:
    公共类ControllerTab扩展Activity实现OnItemClickListener {

    //BluetoothAdapter          BTAdapter;
    public static BluetoothAdapter          BTAdapter;
    //Intent
    private static final int    REQUEST_DEVICE_CONNECT = 1;
    private static final int    REQUEST_ENABLE_BLUETOOTH = 2;
    private static final int    REQUEST_ABOUTS = 3;
    //
    private String connectedDeviceName = null;
    //Message types sent from the Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int RECIEVE_MESSAGE = 6;
  //Will be used in BluetoothCommandSrvice jave file
        public static final String TOAST = "toast";
        public static final String DEVICENAME = "device name";

    //@@@@@@@for the controller
    public static final String tagStateCTRL = "Controller";
    private OutputStream outStream = null;
    private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private static String address = "00:00:00:00:00:00"; // Insert your bluetooth devices MAC address
    private StringBuilder sb = new StringBuilder();
    Button btn_d1_on, btn_d1_off, btn_d2_on, btn_d2_off;
    Switch switch_d1, switch_d2;
    TextView textDevice1;

        //for the switch
        private final static Integer[] ids = { R.id.switch1, R.id.switch2 };


        //object for bluetooth command service
        private BluetoothCommandService commandService = null;

        //listview, swtchcontrol
        private ArrayAdapter<String> switchControls;

        private TextView deviceID;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        DatabaseHandler db = new DatabaseHandler(this);
        List<Device> deviceList = db.getAllDevices();
        if (deviceList.size()!=0) {
            ListView list = getListView();
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
                    deviceID = (TextView) view.findViewById(R.id.deviceId);
                    String valDeviceId = deviceID.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(), EditDeviceName.class);
                    objIndent.putExtra("deviceID", valDeviceId);
                    startActivity(objIndent);
                }
            });
// Initialize the BluetoothChatService to perform bluetooth connections
         commandService = new BluetoothCommandService(this, bluetoothHandler);
         BTAdapter = BluetoothAdapter.getDefaultAdapter();

        switch_d1 = (Switch) findViewById(R.id.switch1);
        switch_d2 = (Switch) findViewById(R.id.switch2);

            registerOnCheckedListener(ids);
 }}
    private ListView getListView() {
        // TODO Auto-generated method stub
        return null;
    }
@SuppressLint("NewApi")
    private void registerOnCheckedListener(Integer... ids)
    {
        for (int i=0; i<ids.length; i++)
        {
            Integer id = ids[i];
            Switch switchControl = (Switch) findViewById(id);
            switchControl.setOnCheckedChangeListener((OnCheckedChangeListener) this);
        }
    }

    //@Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        switch (buttonView.getId())
        {
            case R.id.switch1:
                    if (isChecked)
                        //ga error man sooooo "surround with try/catch" pra mwala.. ok? ^_^
                        try {
                            String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                            if (address.equals(MainActivity.HC05))
                            {
                                sendData("1");
                            }
                            else
                            {
                                Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    else
                        try {
                            String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                            if (address.equals(MainActivity.HC05))
                            {
                                sendData("3");
                            }
                            else
                            {
                                Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    return;
            case R.id.switch2:
                if (isChecked)
                    try {
                        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                        if (address.equals(MainActivity.HC05))
                        {
                            sendData("2");
                        }
                        else
                        {
                            Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                else
                    try {
                        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                        if (address.equals(MainActivity.HC05))
                        {
                            sendData("4");
                        }
                        else
                        {
                            Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    }
...

最佳答案

这是您当前拥有的:

list = getListView()

...

private ListView getListView() {
    // TODO Auto-generated method stub
    return null;
}


您需要实现getListView

09-16 01:56