添加蓝牙按钮后,我的应用崩溃了

时间:2019-11-29 21:13:56

标签: android button bluetooth null crush

我是Android Studio的新手 我想通过蓝牙HC-06将数据从Arduino发送到android 我从AndroidStudio的模板(导航抽屉活动)开始编写代码。 最初一切都还好,但是当我想在帮助中将蓝牙按钮与SetOnClickListener帮助一起添加时,噩梦就开始了。 1.其外观从此enter image description here

对此enter image description here。为了清楚起见:导航栏和其他工具消失了,只显示了主页片段。 2.当按此片段上的Bluetooth按钮时,我的应用程序关闭。  我尝试遵循logcat,但无法解决问题。

请帮我提建议 最良好的问候 ps。下面是我的MainActivity.java文件

package com.example.myecg2;

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

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;


public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private TextView Tekst;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Savollaringiz bo\'lsa Xat yozing", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        final int REQUEST_ENABLE_BT = 1;

        setContentView(R.layout.fragment_home);
      final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        Button button =findViewById(R.id.button6);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (btAdapter == null) {
                    Tekst.setText("Bluetooth NOT support");
                    return;
                } else {
                    if (btAdapter.isEnabled()) {
                        Tekst.setText("Bluetooth is currently in device discovery process.");

                        Tekst.append("\nPaired Devices are:");
                        Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                        for (BluetoothDevice device : devices) {
                            Tekst.append("\nDevice" + device.getName() + "," + device);
                        }
                    } else {

                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                }
            }
        }
        );}


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

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}
以及res / layout

中的content_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="394dp"
        android:layout_height="218dp"
        android:text="@string/matn"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button6" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="116dp"

        android:text="@string/LeadI"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text_home"/>
</androidx.constraintlayout.widget.ConstraintLayout>

和LogCat中给出的错误 2019-11-30 02:09:01.342 13088-13088 / com.example.myecg2 D / AndroidRuntime:关闭VM 2019-11-30 02:09:01.343 13088-13088 / com.example.myecg2 E / AndroidRuntime:FATAL EXCEPTION:main     流程:com.example.myecg2,PID:13088     java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void android.widget.TextView.setText(java.lang.CharSequence)”         在com.example.myecg2.MainActivity $ 2.onClick(MainActivity.java:75)         在android.view.View.performClick(View.java:6256)         在android.view.View $ PerformClick.run(View.java:24701)         在android.os.Handler.handleCallback(Handler.java:789)         在android.os.Handler.dispatchMessage(Handler.java:98)         在android.os.Looper.loop(Looper.java:164)         在android.app.ActivityThread.main(ActivityThread.java:6541)         在java.lang.reflect.Method.invoke(本机方法)         在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

1 个答案:

答案 0 :(得分:0)

Tekst为空,即您永远不会实例化该变量。

您的日志在这里说:

java.lang.NullPointerException: 
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 
at com.example.myecg2.MainActivity$2.onClick(MainActivity.java:75) 
at ...

它甚至说出错误发生在的类MainActivity,方法发生在onClick的方法名称以及错误行:75

在尝试访问变量(即第75行的访问)之前,您缺少在findViewByIdTekst实例化onCreate变量的操作。


边注:

您两次致电setContentView。你不应该那样做。删除第二个。

Java和Kotlin中的变量名应以小写字母开头,以帮助您将它们与其他事物区分开。将Tekst重命名为tekst。这也是错字吗?也许应该是test,可以帮助您调试的更好的名称是testTextView