NullPointerException异常
所以我的代码一直在正常工作,并且我为GUI添加了一些额外的功能,现在突然间我得到一个空指针异常。我无法弄清楚为了做到这一点,我可以改变什么。我已经把代码弄糟了,直到错误出现的地方。NullPointerException异常
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
我希望你已经发布了全班...我们不知道你是否切断了原因......例如,一个可能的原因;
是stateBluetooth
声明为类变量还是局部变量?如果你滑倒并在onCreate中创建它,那可能就是为什么你使用另一种方法获得NPE的原因。
我刚刚添加了我的其他代码,对此感到抱歉。 – JuiCe
由于CheckBluetoothState()是问题区域和堆栈跟踪不给多的信息,请尝试用尝试捕捉周围并打印整个错误。也可以尝试通过在每个点捕获异常来调试它。有了很少的信息,这就是我所能想到的。通过从catch块中发布错误来更新问题。希望这可以帮助。
那么LogCat说NullPointerException,并在其行165.这是行“stateBluetooth.setText(”蓝牙不支持“);” CheckBluetoothState内 – JuiCe
myBtAdapter = null;,我有这个初始化的问题
所以将其更改为:
myBtAdapter = BluetoothAdapter.getDefaultAdapter;
宾果!
什么行是165? ('CheckBlueToothState(AndroidBluetooth.java:165)')? – Nanne
'stateBluetooth'似乎是'null'。 'R.lay.main'中是否存在'R.id.titleTvRight'? – Floern
如果R.id.titleTv确实像Foern提到的那样存在,请尝试将onCreate()逻辑的其余部分放在onFinishInflate() –