我正在使用我的arduino uno和HC-05蓝牙模块创建家庭自动化Android应用程序。一切都很好。它可以扫描,连接,打开/关闭蓝牙,使用按钮和开关控制打开和关闭灯泡,但应用程序设计糟糕而简单。所以我决定使用Tab Widget。问题是只有在每个选项卡中使用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中创建的Tab Widget中。
所以这是我在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和我的代码。
答案 0 :(得分:0)
试试这个..
您必须设置setContentView(R.layout.yourxmllayoutname);
,然后只有Buttons
才能获得参考。如果您想以编程方式添加TextView
,请尝试添加到主要布局的addview
。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmllayoutname);
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);
LinearLayout main_lay = (LinearLayout)findViewById(R.id.main_lay_id);
TextView textview = new TextView(this);
textview.setText("Controller Tab");
main_lay.addview(textview);
答案 1 :(得分:0)
您收到NullPointerException,因为您尚未在类中初始化 BTAdapter ,而是在onStart()中使用它而不进行初始化。