Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/208.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android NullPointerException不知从何而来_Android_User Interface_Bluetooth_Nullpointerexception - Fatal编程技术网

Android NullPointerException不知从何而来

Android NullPointerException不知从何而来,android,user-interface,bluetooth,nullpointerexception,Android,User Interface,Bluetooth,Nullpointerexception,因此,我的代码工作得很好,我在GUI中添加了一些额外的功能,现在突然出现了空指针异常。我不知道我能做些什么来实现这一点。我已将代码简化到错误所在的位置 public class AndroidBluetooth extends Activity { /** Called when the activity is first created. */ private static BluetoothAdapter myBtAdapter; private static BluetoothDevic

因此,我的代码工作得很好,我在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();
}

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

我希望你能把全班的人都贴出来。。。我们不知道你是否已经切断了原因。。。例如,一个可能的原因

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

myBtAdapter=null,我在初始化时遇到问题

因此,将其更改为:

myBtAdapter=BluetoothAdapter.getDefaultAdapter


宾果

165是哪一行?(
checkBluetooth状态(AndroidBluetooth.java:165)
)?
状态Bluetooth
似乎是
null
R.id.titleTvRight
是否存在于
R.layout.main
中?如果R.id.titleTv确实存在,请尝试将其余的onCreate()逻辑放入onFinishInflate()中,如果您是对的,谢谢。我所做的是创建一个单独的XML文件,试图创建一个自定义菜单栏,titleTvRight就是在这里初始化的。希望我能接受你写的答案。好吧,LogCat说是NullPointerException,它在第165行。这是CheckBluetoothState中的行“stateBooth.setText(“不支持蓝牙”);”
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