java - 添加选项卡小部件功能后出现空指针异常错误

标签 java android

我正在使用我的 arduino uno 和 HC-05 蓝牙模块创建一个家庭自动化 Android 应用程序。一切都已经很好了。它可以扫描、连接、开/关蓝牙、使用按钮和开关控制控制灯泡的开和关,但应用程序的设计很糟糕且朴素。所以我决定使用选项卡小部件。问题是该选项卡仅在我在每个选项卡中使用 TextView 时才有效。每次我使用已经可以控制灯泡的代码在手机中运行该应用程序时,它都会立即停止并崩溃。从昨天开始我已经调试了很多次,但 LogCat 中仍然存在 NullPointerException。

以下是 LogCat 中的列表:

01-12 01:10:35.298: E/AndroidRuntime(27771): FATAL EXCEPTION: main
01-12 01:10:35.298: E/AndroidRuntime(27771): 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
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.access$600(ActivityThread.java:162)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.os.Handler.dispatchMessage(Handler.java:107)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.os.Looper.loop(Looper.java:194)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.main(ActivityThread.java:5371)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at java.lang.reflect.Method.invokeNative(Native Method)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at java.lang.reflect.Method.invoke(Method.java:525)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at dalvik.system.NativeStart.main(Native Method)
01-12 01:10:35.298: E/AndroidRuntime(27771): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.ControllerTab}: java.lang.NullPointerException
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:2186)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.widget.TabHost.setCurrentTab(TabHost.java:413)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.widget.TabHost.addTab(TabHost.java:240)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at com.example.javac101.MainActivity.onCreate(MainActivity.java:124)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.Activity.performCreate(Activity.java:5122)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
01-12 01:10:35.298: E/AndroidRuntime(27771):    ... 11 more
01-12 01:10:35.298: E/AndroidRuntime(27771): Caused by: java.lang.NullPointerException
01-12 01:10:35.298: E/AndroidRuntime(27771):    at com.example.javac101.ControllerTab.onStart(ControllerTab.java:296)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1167)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.Activity.performStart(Activity.java:5132)
01-12 01:10:35.298: E/AndroidRuntime(27771):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2316)

我相信问题出在我的 ControllerTab.java 上,它位于我在 MainActivity.java 中创建的选项卡小部件内。

这是我在 ControllerTab.java 中的代码:

//public class ControllerTab extends Activity implements OnCheckedChangeListener {
public class ControllerTab extends Activity {

    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;
        //for the switch
        private final static Integer[] ids = { R.id.switch1, R.id.switch2 };


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


    //@@@@@@@@for changing the device_1 name
    TextView device1;
    Button change;
    EditText renameDevice;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*
        TextView textview = new TextView(this);
        textview.setText("Controller Tab");
        setContentView(textview);
        */

        setContentView(R.layout.activity_main);
      //@@@@@@@@@@for the controller    
        btn_d1_on = (Button) findViewById(R.id.device1_on);
        btn_d1_off = (Button) findViewById(R.id.device1_off);
        btn_d2_on = (Button) findViewById(R.id.device2_on);
        btn_d2_off = (Button) findViewById(R.id.device2_off);



         // Initialize the BluetoothChatService to perform bluetooth connections
         commandService = new BluetoothCommandService(this, bluetoothHandler);

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

        //@@@@@@@@for changing the device_1 name
        device1 = (TextView)findViewById(R.id.device1);
        change = (Button)findViewById(R.id.buttonTest);
        renameDevice = (EditText)findViewById(R.id.editTest);
        change.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View arg0) {
            // TODO Auto-generated method stub
                String change_device1 = renameDevice.getText().toString();
                device1.setText(change_device1);
            } 
        });


      //@@@@@@@@@@for the controller
            btn_d1_on.setOnClickListener(new OnClickListener()
            {
                public void onClick(View v)
                {
                    //sendData("1");
                    //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                    //msg.show()
                    try {
                        sendData("1");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });

            //@@@@@@@@@@for the controller
            btn_d1_off.setOnClickListener(new OnClickListener()
            {
                public void onClick(View v)
                {
                    //sendData("0");
                    //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                    //msg.show();
                    try {
                        sendData("3");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });

            //@@@@@@@@@@for the controller
                    btn_d2_on.setOnClickListener(new OnClickListener()
                    {
                        public void onClick(View v)
                        {
                            //sendData("1");
                            //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                            //msg.show()
                            try {
                                sendData("2");
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                    });

                    //@@@@@@@@@@for the controller
                    btn_d2_off.setOnClickListener(new OnClickListener()
                    {
                        public void onClick(View v)
                        {
                            //sendData("0");
                            //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                            //msg.show();
                            try {
                                sendData("4");
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });


                //@@@@@@@@@for the controller
                //SWITCH
                //registerOnCheckedListener(ids);
     }
        /*
  //register all onCheckedChnagedListener for all switch
    //SABTAH BAYET!!!!
    //ang "i" is gabasi sa array sa taas --- "private final static Integer[] ids"
    @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(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 {
                        sendData("1");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                else
                    try {
                        sendData("3");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                return;
            case R.id.switch2:
                if (isChecked)
                    try {
                        sendData("2");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                else
                    try {
                        sendData("4");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    }

    */
    //@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
        {
            commandService.write(BluetoothCommandService.VOL_UP);
            return true;
        }
        else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
        {
            commandService.write(BluetoothCommandService.VOL_DOWN);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
     private void sendData(String message) throws IOException
    //public void sendData(String message) throws IOException  
    //public void sendData(String message)
      {
          byte[] msgBuffer = message.getBytes();

          Log.d(tagStateCTRL, "...Sending data: " + message + "...");

          //outStream.write(msgBuffer);
          BluetoothCommandService.write(msgBuffer);

          /*
          catch (IOException e){
              String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
              if (address.equals("00:00:00:00:00:00")) 
                  msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address in the java code";
              msg = msg +  ".\n\nCheck that the SPP UUID: " + myUUID.toString() + " exists on server.\n\n";

          errorExit("Fatal Error", msg);       
        }
        */

      }

    @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();
        }
    }


        //Will automatically enable and request to be discoverable for 500 sec.gi comment since dili pa sure kung needed pa ba nga ma discoverable
        //if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
        //{
            //Intent discoverableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
            //startActivity(discoverableIntent);
        //}

    @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();
    }

    //This gets information back from the "BluetoothChatService"/"BluetoothCommandService"
        //@SuppressLint("HandlerLeak")
        //private final Handler bluetoothHandler = new Handler(new Handler.Callback()
        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);
                                MainActivity.title.setText(R.string.title_connectedTo);
                                MainActivity.title.append(connectedDeviceName);
                                break;

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

                            case BluetoothCommandService.stateListen:
                            case BluetoothCommandService.stateNothing:
                                //title.setText(getString(R.string.title_notConnected));
                                MainActivity.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);
                    // Get the BLuetoothDevice object
                    BluetoothDevice device = BTAdapter.getRemoteDevice(address);
                    // Attempt to connect to the device
                    commandService.connect(device);
                }
                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();
               }


            }
        }

}

我同时在此代码中注释了开关控件的代码。希望任何人都知道我的代码发生了什么。这将是一个很大的帮助,并且非常感谢。

编辑:我更新了 LogCat 和我的代码。

最佳答案

您收到 NullPointerException 是因为您尚未在类中初始化 BTAdapter,并且您在 onStart() 中使用它而未初始化它。

关于java - 添加选项卡小部件功能后出现空指针异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064732/

相关文章:

android - ListView 项目背景颜色更改

android - 我应该在 Firestore 的字段文档中只写标识符还是写所有数据?

android - 如何查看 Android 智能手机设备的发布日期?

java - 无法通过java触发Jenkins构建

java - 可视化数组列表

android - 使用RandomAccessFile直接从文件读取时,音频样本中的变化?

android - PublishSubject 不适用于firstOrError()

java - 定义与数据库无关的 JPA 对象 uid

javascript - 如何使用 JavaScript 根据变量值隐藏图像?

java - JasperReport- 多页静态报告的最佳方法