所以我的代码工作正常,我在GUI中添加了一些额外的功能,现在我突然得到一个空指针异常。我无法弄清楚我可以改变什么来实现这一目标。我把代码愚蠢到了错误的位置。
public class AndroidBluetooth extends Activity {
/** Called when the activity is first created. */
private static BluetoothAdapter myBtAdapter;
private static BluetoothDevice myBtDevice;
private ArrayAdapter<String> btArrayAdapter;
private ArrayList<BluetoothDevice> btDevicesFound = new ArrayList<BluetoothDevice>();
private Button btnScanDevice;
private TextView stateBluetooth;
private ListView listDevicesFound;
private InputStream iStream;
private OutputStream oStream;
private BluetoothSocket btSocket;
private String newDeviceAddress;
private BroadcastReceiver mReceiver;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static TextView mTitle;
// Name of the connected device
private String mConnectedDeviceName = null;
/**
* Set to true to add debugging code and logging.
*/
public static final boolean DEBUG = true;
/**
* Set to true to log each character received from the remote process to the
* android log, which makes it easier to debug some kinds of problems with
* emulating escape sequences and control codes.
*/
public static final boolean LOG_CHARACTERS_FLAG = DEBUG && false;
/**
* Set to true to log unknown escape sequences.
*/
public static final boolean LOG_UNKNOWN_ESCAPE_SEQUENCES = DEBUG && false;
private static final int REQUEST_ENABLE_BT = 2;
// Member fields
//private final BluetoothAdapter mAdapter;
//private final Handler mHandler;
//private ConnectThread mConnectThread;
//private ConnectedThread mConnectedThread;
//private int mState;
//private EmulatorView mEmulatorView;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
//public boolean customTitleSupported;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//customTitleSupported = requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
// Set up window View
setContentView(R.layout.main);
stateBluetooth = (TextView) findViewById ( R.id.titleTvRight );
startBluetooth();
myBtAdapter = null;
CheckBlueToothState();
//customTitleBar( getText( R.string.app_name).toString(), getText( R.string.app_name).toString() );
}
/**
public void customTitleBar( String left, String right ) {
if( right.length() > 20 ) right = right.substring( 0, 20 );
if( customTitleSupported ) {
getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.customlayoutbar );
TextView titleTvLeft = (TextView) findViewById( R.id.titleTvLeft );
TextView titleTvRight = (TextView) findViewById( R.id.titleTvRight );
titleTvLeft.setText( left );
titleTvRight.setText( right );
}
}
*/
public boolean onCreateOptionsMenu( Menu menu ) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.option_menu, menu );
return true;
}
public boolean onOptionsItemSelected( MenuItem item ) {
switch( item.getItemId() ) {
case R.id.connect:
startActivityForResult( new Intent( this, DeviceList.class ), REQUEST_CONNECT_DEVICE );
return true;
case R.id.preferences:
return true;
default:
return super.onContextItemSelected( item );
}
}
private void CheckBlueToothState() {
Log.i("HUH", "0");
if( myBtAdapter == null ) {
Log.i("HUH", "1");
stateBluetooth.setText("Bluetooth NOT supported" );
} else {
Log.i("HUH","2");
if( myBtAdapter.isEnabled() ) {
Log.i("HUH","3");
if( myBtAdapter.isDiscovering() ) {
Log.i("HUH","4");
stateBluetooth.setText( "Bluetooth is currently " +
"in device discovery process." );
} else {
Log.i("HUH","5");
stateBluetooth.setText( "Bluetooth is Enabled." );
btnScanDevice.setEnabled( true );
}
} else {
Log.i("HUH","6");
stateBluetooth.setText( "Bluetooth is NOT enabled" );
Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
startActivityForResult( enableBtIntent, REQUEST_ENABLE_BT );
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener() {
public void onClick( View arg0 ) {
}
};
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
if( requestCode == REQUEST_ENABLE_BT ) {
CheckBlueToothState();
}
}
//In SDK15 (4.0.3) this method is now public as
//Bluetooth.fetchUuisWithSdp() and BluetoothDevice.getUuids()
public ParcelUuid[] servicesFromDevice(BluetoothDevice device) {
try {
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("getUuids", par);
Object[] args = {};
ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
return retval;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
public void onReceive( Context context, Intent intent ) {
String action = intent.getAction();
if( BluetoothDevice.ACTION_FOUND.equals( action ) ) {
BluetoothDevice btDevice = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
btDevicesFound.add( btDevice );
btArrayAdapter.add( btDevice.getName() + "\n" + btDevice.getAddress() );
btArrayAdapter.notifyDataSetChanged();
}
}
};
public static void startBluetooth(){
try {
myBtAdapter = BluetoothAdapter.getDefaultAdapter();
myBtAdapter.enable();
} catch ( NullPointerException ex ) {
Log.e( "Bluetooth", "Device not available" );
}
}
public static void stopBluetooth() {
myBtAdapter.disable();
}
}
这是LogCat:
06-13 16:34:33.654: I/HUH(17008): 0
06-13 16:34:33.654: I/HUH(17008): 1
06-13 16:34:33.662: D/AndroidRuntime(17008): Shutting down VM
06-13 16:34:33.662: W/dalvikvm(17008): threadid=1: thread exiting with uncaught exception (group=0x40015560)
06-13 16:34:33.662: E/AndroidRuntime(17008): FATAL EXCEPTION: main
06-13 16:34:33.662: E/AndroidRuntime(17008): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidBluetooth/com.exercise.AndroidBluetooth.AndroidBluetooth}: java.lang.NullPointerException
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.os.Handler.dispatchMessage(Handler.java:99)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.os.Looper.loop(Looper.java:130)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-13 16:34:33.662: E/AndroidRuntime(17008): at java.lang.reflect.Method.invokeNative(Native Method)
06-13 16:34:33.662: E/AndroidRuntime(17008): at java.lang.reflect.Method.invoke(Method.java:507)
06-13 16:34:33.662: E/AndroidRuntime(17008): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-13 16:34:33.662: E/AndroidRuntime(17008): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-13 16:34:33.662: E/AndroidRuntime(17008): at dalvik.system.NativeStart.main(Native Method)
06-13 16:34:33.662: E/AndroidRuntime(17008): Caused by: java.lang.NullPointerException
06-13 16:34:33.662: E/AndroidRuntime(17008): at com.exercise.AndroidBluetooth.AndroidBluetooth.CheckBlueToothState(AndroidBluetooth.java:165)
06-13 16:34:33.662: E/AndroidRuntime(17008): at com.exercise.AndroidBluetooth.AndroidBluetooth.onCreate(AndroidBluetooth.java:124)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-13 16:34:33.662: E/AndroidRuntime(17008): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-13 16:34:33.662: E/AndroidRuntime(17008): ... 11 more
答案 0 :(得分:1)
由于CheckBluetoothState()是问题区域,并且堆栈跟踪没有提供太多信息,请尝试使用try catch包围它并打印整个错误。还可以通过在每个单点捕获异常来尝试调试它。随着小信息,这就是我所能提出的。通过从catch块发布错误来更新问题。希望这可以帮助。
答案 1 :(得分:1)
我希望你发布了全班...我们不知道你是否已经删除了原因......例如,可能的原因;
stateBluetooth
是声明为类变量还是局部变量?如果你滑了。并在onCreate中创建它,这可能就是你在另一种方法中获得NPE的原因。
答案 2 :(得分:0)
myBtAdapter = null; ,我遇到了初始化的问题
所以将其改为:
myBtAdapter = BluetoothAdapter.getDefaultAdapter;
宾果!