添加蓝牙连接代码后,Android Studio App崩溃

问题描述 投票:2回答:2

我目前正在一个应用程序通过蓝牙控制arduino。我为菜单添加了一些活动等等。昨天我添加了一个新的活动,用于将我的设备连接到蓝牙模块。

甚至可以在一个活动中连接到设备并在另一个活动中实际控制(发送信件)吗?

有了这个说,每当我尝试使用蓝牙代码打开活动时,应用程序崩溃。每个其他活动都没有任何问题。

我希望有人可以提供帮助。

这是我的代码:

MainActivity.java(将控制模块的活动):

package com.car.bluetooth.bluetoothcar;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {






@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //MENÜPUNKTE
    if (id == R.id.action_settings) {
        Intent settingsintent = new Intent(MainActivity.this,
                settingsactivity.class);
                startActivity(settingsintent);
                return false;
    }
    if (id == R.id.action_connect) {
        Intent connectintent = new Intent(MainActivity.this,
                connectactivity.class);
                startActivity(connectintent);
                return false;
    }

    return super.onOptionsItemSelected(item);
}


//SeekBars

private SeekBar seekBarGas;
private TextView textViewGas;

private SeekBar seekBarSteering;
private TextView textViewSteering;

private CheckBox backwards_checkBox;
boolean rückwärts_var = false;

boolean safeMode;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    seekBarGas = (SeekBar) findViewById(R.id.seekBarGas);
    textViewGas = (TextView) findViewById(R.id.textViewGas);
    seekBarGas.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            textViewGas.setText(progress + "  /  " + seekBarGas.getMax());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            seekBarGas.setProgress(0);
        }
    });

    seekBarSteering = (SeekBar) findViewById(R.id.seekBarSteering);
    textViewSteering = (TextView) findViewById(R.id.textViewSteering);
    seekBarSteering.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            textViewSteering.setText(progress + "  /  " + seekBarSteering.getMax());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            seekBarSteering.setProgress(3);
        }
    });


    //GET DATA Settings

    Intent safeMode_Intent = getIntent();
    safeMode = safeMode_Intent.getBooleanExtra("safeMode", false);


    //Rückwärts

    CheckBox backwards_checkBox=(CheckBox)findViewById(R.id.backwards_checkBox);

    backwards_checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (((CheckBox)v).isChecked()) {
                Toast.makeText(getApplicationContext(), "Rückwärts", Toast.LENGTH_SHORT).show();
                rückwärts_var = true;

                if (safeMode == true) {
                    seekBarGas.setMax(2);
                }
            }
            else{
                Toast.makeText(getApplicationContext(), "Vorwärts", Toast.LENGTH_SHORT).show();
                rückwärts_var = false;

                if (safeMode == true){
                seekBarGas.setMax(5);
                }
        }
    }
        });


    //Bluetooth



    if (btAdapter == null){
        Toast.makeText(getApplicationContext(), "Bluetooth wird auf diesem Gerät nicht unterstützt", Toast.LENGTH_LONG).show();
    }






}





}

BT_Classic.java(连接到模块的活动):

package com.car.bluetooth.bluetoothcar;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;


public class BT_Classic extends AppCompatActivity {

private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
ListView list;

private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bt__classic);

    pairedButton = (Button) findViewById(R.id.pairedButton);
    discoveredButton = (Button) findViewById(R.id.discoveredButton);

    list = (ListView) findViewById(R.id.list) ;



    //Pairing Button

    pairedButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();

            ArrayList<String> devices = new ArrayList<String>();

            for (BluetoothDevice bt : pairedDevices){
                devices.add(bt.getName());
            }

            ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
            list.setAdapter(arrayAdapter);
        }
    });

    discoveredButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(!btAdapter.isDiscovering()){
                Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(bton, REQUEST_DISCOVERABLE);
            }


        }
    });

    btonButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(bton, REQUEST_ENABLED);
        }
    });

    btoffButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btAdapter.disable();
        }
    });










}
}

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.car.bluetooth.bluetoothcar">

<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="Bluetooth Car"
        android:screenOrientation="landscape"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".connectactivity"
        android:label="Connect"
        android:screenOrientation="landscape" />
    <activity
        android:name=".settingsactivity"
        android:label="Settings"
        android:screenOrientation="landscape" />
    <activity
        android:name=".BT_LE"
        android:label="Connect Bluetooth Low Energy"
        android:screenOrientation="landscape"/>
    <activity
        android:name=".BT_Classic"
        android:label="Connect Bluetooth Classic"
        android:screenOrientation="landscape"
        ></activity>
</application>

build.gradle(模块:app):

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.car.bluetooth.bluetoothcar"
    minSdkVersion '16'
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha05'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha05'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
implementation 'com.google.android.material:material:1.0.0-beta01'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

系统崩溃日志:

2018-09-12 17:25:36.957 10178-10178/com.car.bluetooth.bluetoothcar 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.car.bluetooth.bluetoothcar, PID: 10178
java.lang.RuntimeException: Unable to start activity  


ComponentInfo{com.car.bluetooth.bluetoothcar/com.car.bluetooth.bluetoothcar.BT_Classic}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at 
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
        at 
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6592)
        at java.lang.reflect.Method.invoke(Native Method)
        at 
    com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.car.bluetooth.bluetoothcar.BT_Classic.onCreate(BT_Classic.java:78)
        at android.app.Activity.performCreate(Activity.java:6984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6592) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 
java android android-studio bluetooth android-bluetooth
2个回答
1
投票

btonButtonbtoffButton未初始化且等于null。

您应该使用findViewById()初始化它们,就像使用pairedButton一样

btonButton = (Button) findViewById(R.id.put_here_btn_on_id);
btoffButton = (Button) findViewById(R.id.put_here_btn_off_id);

1
投票

btonButton和btoffButton尚未初始化然后你调用setonClickListener这导致NPE

onCreate内部初始化如下:

btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
© www.soinside.com 2019 - 2024. All rights reserved.