Nullpointer exception when trying to use Bluetooth

邮差的信 提交于 2019-12-11 10:17:14

问题


I'm trying to create an Android application that uses the Bluetooth of the device. However, when I try to emulate the application, it gives me this error: unfortunately Application has stopped.

I've searched for a solution but for the problem, and I've done the following:

  1. Use an actual device instead of the emulator since Bluetooth functionality cannot be emulated
  2. Modify the code according to some suggestions I found online
  3. Use a VM instead of the normal emulator on a Bluetooth-capable computer.

All of the above attempts proved futile and were of no avail.

My java file:

package com.example.application;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity{
/** Called when the activity is first created. */
private BluetoothAdapter btAdapter;

public TextView statusUpdate;
public Button connect;
public Button disconnect;
public ImageView logo;

BroadcastReceiver bluetoothState = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
        String prevStateExtra=BluetoothAdapter.EXTRA_PREVIOUS_STATE;
        String stateExtra=BluetoothAdapter.EXTRA_STATE;
        int state = intent.getIntExtra(prevStateExtra,  -1);
        int previousState = intent.getIntExtra(prevStateExtra, -1);
        String toastText="";
        switch(state){
        case(BluetoothAdapter.STATE_TURNING_ON) :
        {
            toastText="Bluetooth turning on";
            Toast.makeText(MainActivity.this, toastText,          Toast.LENGTH_SHORT).show();
            break;
        }   
        case(BluetoothAdapter.STATE_ON) :
        {
            toastText="Bluetooth on";
            Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
            setupUI();
            break;
        }   
        case(BluetoothAdapter.STATE_TURNING_OFF) :
        {
            toastText="Bluetooth turning off";
            Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
            break;
        }       
        case(BluetoothAdapter.STATE_OFF) :
        {
            toastText="Bluetooth off";
            Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
            setupUI();
            break;
        }

        }

    }


};
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
setupUI();  
}//end onCreate



private void setupUI(){
//get references
//final TextView statusUpdate = (TextView) findViewById(R.id.result);
final Button connect = (Button)findViewById(R.id.connect);
final Button disconnect = (Button)findViewById(R.id.disconnect);
//final ImageView logo = (ImageView)findviewById(R.id.logo);
//set display view

disconnect.setVisibility(View.GONE);
logo.setVisibility(View.GONE);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter.isEnabled()){
    String address = btAdapter.getAddress();
    String name = btAdapter.getName();
    String statusText = name + " : " + address;
    statusUpdate.setText(statusText);
}
else{
    connect.setVisibility(View.VISIBLE);
    statusUpdate.setText("Bluetooth is not on");
}

connect.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v){
        String actionStateChanged =     BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED;
        String actionRequestEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;
        IntentFilter filter = new IntentFilter(actionStateChanged);
        registerReceiver(bluetoothState, filter);
        startActivityForResult(new Intent(actionRequestEnable), 0);


    }

}); //end connect onClickListener

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

    }

}); //end disconnect onClickListener

}
} //end setupUI

Main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="1dp" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:gravity="center"
    android:text="Sherline Android App"
    android:textColor="#0000ff"
    android:textSize="20dp"
    android:textStyle="bold" />

    <requestFocus />

    <Button
        android:id="@+id/connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="36dp"
        android:text="Connect Bluetooth"
        android:textSize="12sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:layout_alignTop="@+id/connect"
        android:layout_toRightOf="@+id/disconnect"
        android:background="#808080"
        android:ems="10"
        android:hint="G-code goes here..."
        android:inputType="textMultiLine"
        android:textColorHint="#FFFFFFFF"
        android:width="150dp" >                     

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/disconnect"
        android:layout_alignRight="@+id/disconnect"
        android:layout_below="@+id/disconnect"
        android:radius="3dp"
        android:text="Stop"
        android:textSize="12dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Button01"
        android:layout_alignRight="@+id/Button01"
        android:layout_centerVertical="true"
        android:radius="3dp"
        android:text="Pause"
        android:textSize="12dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Button03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Button02"
        android:layout_alignRight="@+id/Button02"
        android:layout_below="@+id/Button02"
        android:radius="3dp"
        android:text="Resume"
        android:textSize="12dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/disconnect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/connect"
        android:layout_below="@+id/connect"
        android:radius="3dp"
        android:text="Disconnect Bluetooth"
        android:textSize="12sp"
        android:textStyle="bold" />

</RelativeLayout>

logcat shows the following error(s):

01-31 10:34:41.511: E/AndroidRuntime(978): FATAL EXCEPTION: main
01-31 10:34:41.511: E/AndroidRuntime(978): java.lang.RuntimeException: Unable to start          activity ComponentInfo{com.example.application/com.example.application.MainActivity}:     java.lang.NullPointerException
01-31 10:34:41.511: E/AndroidRuntime(978):  at         android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-31 10:34:41.511: E/AndroidRuntime(978):  at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.os.Looper.loop(Looper.java:137)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.ActivityThread.main(ActivityThread.java:5039)
01-31 10:34:41.511: E/AndroidRuntime(978):  at java.lang.reflect.Method.invokeNative(Native Method)
01-31 10:34:41.511: E/AndroidRuntime(978):  at java.lang.reflect.Method.invoke(Method.java:511)
01-31 10:34:41.511: E/AndroidRuntime(978):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-31 10:34:41.511: E/AndroidRuntime(978):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-31 10:34:41.511: E/AndroidRuntime(978):  at dalvik.system.NativeStart.main(Native     Method)
01-31 10:34:41.511: E/AndroidRuntime(978): Caused by: java.lang.NullPointerException
01-31 10:34:41.511: E/AndroidRuntime(978):  at     com.example.application.MainActivity.setupUI(MainActivity.java:87)
01-31 10:34:41.511: E/AndroidRuntime(978):  at com.example.application.MainActivity.onCreate(MainActivity.java:73)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.Activity.performCreate(Activity.java:5104)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-31 10:34:41.511: E/AndroidRuntime(978):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-31 10:34:41.511: E/AndroidRuntime(978):  ... 11 more
01-31 10:54:41.175: E/AndroidRuntime(1149): FATAL EXCEPTION: main
01-31 10:54:41.175: E/AndroidRuntime(1149): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.example.application/com.example.application.MainActivity}:     java.lang.NullPointerException
01-31 10:54:41.175: E/AndroidRuntime(1149):     at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at     android.app.ActivityThread.access$600(ActivityThread.java:141)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.os.Looper.loop(Looper.java:137)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.app.ActivityThread.main(ActivityThread.java:5039)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at java.lang.reflect.Method.invokeNative(Native Method)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at java.lang.reflect.Method.invoke(Method.java:511)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at dalvik.system.NativeStart.main(Native Method)
01-31 10:54:41.175: E/AndroidRuntime(1149): Caused by: java.lang.NullPointerException
01-31 10:54:41.175: E/AndroidRuntime(1149):     at com.example.application.MainActivity.setupUI(MainActivity.java:87)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at com.example.application.MainActivity.onCreate(MainActivity.java:73)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.app.Activity.performCreate(Activity.java:5104)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-31 10:54:41.175: E/AndroidRuntime(1149):     at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-31 10:54:41.175: E/AndroidRuntime(1149):     ... 11 more

Please help! Thanks!


回答1:


Well, you are getting NullPointerException, and there may be 2 cases of interest.

  1. statusUpdate, and logo variables are NULL, but other answers already explaining that.

  2. BluetoothAdapter.getDefaultAdapter() may return NULL if bluetooth is not supported on hardware. So you need to handle that case too..

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    if(btAdapter != null && btAdapter.isEnabled()){  // see changes in this line..
    



回答2:


The problem is that there is null Pointer on this line:

       logo.setVisibility(View.GONE);

Uncomment this line:

         //final ImageView logo = (ImageView)findviewById(R.id.logo);

EDIT: Same problem with statusUpdate.




回答3:


one problem... that component isnt wired to your layout:

statusUpdate.setText(statusText);

I think you need something like this:

statusUpdate = (TextView)findViewById(R.id.textView1);


来源:https://stackoverflow.com/questions/14624281/nullpointer-exception-when-trying-to-use-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!