null对象引用android

时间:2017-01-01 02:28:53

标签: android bluetooth java-threads

我试图建立一个可以:

的应用程序

在三个文本视图中显示当前加速计读数 通过蓝牙将加速度计读数发送到PC /笔记本电脑/ Mac上的串行终端。

我使用Coolterm作为串行终端模拟器,下面是我的尝试 问题是当我打开它时应用程序正在崩溃,而下面是我抓住的例外

package com.sajad.bluetooth_acc;

import android.app.Activity;

import android.bluetooth.BluetoothDevice;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import android.os.Bundle;

import android.os.Handler;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;



import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothSocket;
import android.content.Intent;

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;


public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager sensorManager;

    TextView xCoor; // declare X axis object
    TextView yCoor; // declare Y axis object
    TextView zCoor; // declare Z axis object


    private Button btsend;




    private BluetoothAdapter mBluetoothAdapter ;
    private BluetoothSocket btSocket ;


    private ConnectedThread mConnectedThread;


    // SPP UUID service - this should work for most devices
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // String for MAC address
    private static String address;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        xCoor = (TextView) findViewById(R.id.xcoor); // create X axis object
        yCoor = (TextView) findViewById(R.id.ycoor); // create Y axis object
        zCoor = (TextView) findViewById(R.id.zcoor); // create Z axis object

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // add listener. The listener will be  (this) class
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);


                checkBTState();







        btsend = (Button) findViewById(R.id.btsend);
        btsend.setOnClickListener(btToggleOnClickListener);
    }


    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void onSensorChanged(SensorEvent event) {

        // check sensor type
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

            // assign directions
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            xCoor.setText("X: " + x);
            yCoor.setText("Y: " + y);
            zCoor.setText("Z: " + z);
        }


    }



    // Click event on Button
    private OnClickListener btToggleOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            TextView edtx = (TextView) findViewById(R.id.xcoor);
            TextView edty = (TextView) findViewById(R.id.ycoor);
            TextView edtz = (TextView) findViewById(R.id.zcoor);
            String x_val = edtx.getText().toString();
            String y_val = edty.getText().toString();
            String z_val = edtz.getText().toString();

            String XYZ =
            new StringBuilder()
                    .append(x_val)
                    .append(y_val)
                    .append(z_val)
                    .toString();

            mConnectedThread.write(XYZ);    // Send via Bluetooth
            Toast.makeText(getBaseContext(), "accelerometer readings sent !", Toast.LENGTH_SHORT).show();
           // OutputStream mmOutStream = null;






        }
    };




    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

        return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
        //creates secure outgoing connecetion with BT device using UUID
    }

    @Override
    public void onResume() {
        super.onResume();



        //Get the MAC address from the DeviceListActivty via EXTRA
        address = ("74:E5:43:72:0E:27");

        //create device and set the MAC address
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }
        // Establish the Bluetooth socket connection.
        try
        {
            btSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            try
            {
                btSocket.close();
            } catch (IOException e2)
            {
                e2.printStackTrace();
            }
        }
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();

        // send a character when resuming.beginning transmission to check device is connected
        //If it is not an exception will be thrown in the write method and finish() will be called
        mConnectedThread.write("x");
    }

    @Override
    public void onPause()
    {
        super.onPause();
        try
        {
            //Don't leave Bluetooth sockets open when leaving activity
            btSocket.close();

        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }

    //Checks that the Android device Bluetooth is available and prompts to be turned on if off
    private void checkBTState() {

        if(mBluetoothAdapter==null) {
            Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
        } else {
            if (mBluetoothAdapter.isEnabled()) {
            } else {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

//create new class for connect thread
private class ConnectedThread extends Thread {

    private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {

        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection

            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
        }


        mmOutStream = tmpOut;
    }

    public void run() {
    }

        //write method
        public void write (String input){
            byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
            try {
                mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
            } catch (IOException e) {
                //if you cannot write, close the application
                Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                finish();

            }
        }

    }
}

LOG



01-01 02:14:49.636 30800-30800/com.sajad.bluetooth_acc E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.sajad.bluetooth_acc, PID: 30800
                                                                         java.lang.RuntimeException: Unable to resume activity {com.sajad.bluetooth_acc/com.sajad.bluetooth_acc.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on a null object reference
                                                                             at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3160)
                                                                             at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529)
                                                                             at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:234)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5526)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on a null object reference
                                                                             at com.sajad.bluetooth_acc.MainActivity.onResume(MainActivity.java:171)
                                                                             at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
                                                                             at android.app.Activity.performResume(Activity.java:6361)
                                                                             at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3149)
                                                                             at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191) 
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529) 
                                                                             at android.app.ActivityThread.access$900(ActivityThread.java:154) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             at android.os.Looper.loop(Looper.java:234) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5526) 
                                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 




0 个答案:

没有答案