0

所以我的代码一直运行良好,我在 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
4

3 回答 3

1

由于 CheckBluetoothState () 是问题区域并且堆栈跟踪没有提供太多信息,请尝试用 try catch 包围它并打印整个错误。还可以尝试通过在每个点捕获异常来调试它。有了很少的信息,这就是我所能建议的。通过从 catch 块中发布错误来更新问题。希望这可以帮助。

于 2012-06-13T20:52:53.263 回答
1

我希望你把全班都贴出来了……我们不知道你是否排除了原因……例如,一个可能的原因;

stateBluetooth声明为类变量还是局部变量?如果您在 onCreate 中滑倒并创建它,这可能就是您在另一种方法中获得 NPE 的原因。

于 2012-06-13T22:21:30.593 回答
0

myBtAdapter = null; ,我有这个初始化的问题

所以将其更改为:

myBtAdapter = BluetoothAdapter.getDefaultAdapter;

答对了!

于 2014-06-26T10:12:34.860 回答