【问题标题】:crash when using outputstream android studio使用 outputstream android studio 时崩溃
【发布时间】:2015-06-17 15:04:14
【问题描述】:

每次更改位置时,我都会尝试通过蓝牙将计算出的方位从 android 设备发送到 Arduino。尝试使用 outPutStream 时,应用程序总是崩溃。代码如下:

public class Location_Informaion extends MainActivity implements LocationListener {

private static final String TAG = "bluetooth1";
TextView desiredDest, currentLatitude, currentLongitude, Distance, Bearing, txtArduino;
private LocationManager locationManager;
String provider, message;
private Location location;
double desLatVal, desLonVal, pi;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String macAddress = "30:14:12:02:16:78";
private ConnectedThread mConnectedThread;
Handler h;
final int RECIEVE_MESSAGE = 1;        // Status  for Handler
private StringBuilder sb = new StringBuilder();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pi = 3.14159265359;
    setContentView(R.layout.activity_location__informaion);
    Bundle extras = getIntent().getExtras();
    String desLat = extras.getString("desLat");
    String desLon = extras.getString("desLon");
    desLatVal = Double.parseDouble(desLat);
    desLonVal = Double.parseDouble(desLon);
    desiredDest = (TextView) findViewById(R.id.desiredDestination);
    desiredDest.setText(desLat + "Lat, " + desLon + "Long.");
    message = "180";

    currentLatitude = (TextView) findViewById(R.id.currentLat);
    currentLongitude = (TextView) findViewById(R.id.currentLon);
    txtArduino = (TextView) findViewById(R.id.txtArduino);

    Distance = (TextView) findViewById(R.id.Distance);
    Bearing = (TextView) findViewById(R.id.Bearing);

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!enabled) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        System.out.println("Provider" + provider + "has been selected");
        currentLatitude.setText("Searching for lock");
        currentLongitude.setText("Searching for lock");
        onLocationChanged(location);
    } else {
        currentLatitude.setText("Location is not available");
        currentLongitude.setText("Location is not available");
    }
    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case RECIEVE_MESSAGE:                                                   // if receive massage
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                    sb.append(strIncom);                                                // append string
                    int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                    if (endOfLineIndex > 0) {                                            // if end-of-line,
                        String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                        sb.delete(0, sb.length());                                      // and clear
                        txtArduino.setText("Data from Arduino: " + sbprint);            // update TextView
                    }
                    //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                    break;
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();

}


private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, MY_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(MY_UUID);
}



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

    locationManager.requestLocationUpdates(provider, 0, 0, this);

    Log.d(TAG, "...onResume - try connect...");

    BluetoothDevice device = btAdapter.getRemoteDevice(macAddress);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    btAdapter.cancelDiscovery();

    Log.d(TAG, "...Connecting...");
    try {
        btSocket.connect();
        Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }

    Log.d(TAG, "...Create Socket...");

    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();


}

protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);

    Log.d(TAG, "...In onPause()...");

    try     {
        btSocket.close();
    } catch (IOException e2) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }

}

private void checkBTState() {

    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth not support");
    } else {
        if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth ON...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
}
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;


    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;


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

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {

        byte[] buffer = new byte[256];
        int bytes;


        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(String message) {
        Log.d(TAG, "...Data to send: " + message + "...");
        byte[] msgBuffer = message.getBytes();
        try {
            mmOutStream.write(msgBuffer, 0, msgBuffer.length);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    double lat = (location.getLatitude());
    double lon = (location.getLongitude());
    currentLatitude.setText(String.valueOf(lat));
    currentLongitude.setText(String.valueOf(lon));

    float R = 6371000;
    double latRad = lat / (180 / pi);
    double desLatRad = desLatVal / (180 * pi);
    double changeLat = (desLatVal - lat) / (180 * pi);
    double changeLon = (desLonVal - lon) / (180 / pi);

    double a = Math.sin(changeLat / 2) * Math.sin(changeLat / 2) +
            Math.cos(latRad) * Math.cos(desLatRad) *
                    Math.sin(changeLon / 2) * Math.sin(changeLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    double d = R * c / 1000;

    String distance = String.valueOf(d);

    Distance.setText(distance + "km");

    double y = Math.sin(desLonVal - lon) * Math.cos(desLatVal);
    double x = Math.cos(lat) * Math.sin(desLatVal) -
            Math.sin(lat) * Math.cos(desLatVal) * Math.cos(desLonVal - lon);
    double brng = (Math.atan2(y, x)) * 180 / pi;

    String bearing = String.valueOf(brng);

    Bearing.setText(bearing);

    mConnectedThread.write(bearing);

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enable new provider " + provider, Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
}

}

任何帮助将不胜感激。

06-17 16:34:35.930 11800-11818/com.example.biggus.system_4 I/OpenGLRenderer﹕初始化的 EGL,版本 1.4 06-17 16:34:35.950 11800-11818/com.example.biggus.system_4 I/OpenGLRenderer:为上下文启用了 HWUI 保护,&this =0xb3922088,&mEglDisplay = 1,&mEglConfig = 8 06-17 16:34:35.950 11800-11818/com.example.biggus.system_4 D/OpenGLRenderer: 启用调试模式 0 06-17 16:34:36.090 11800-11800/com.example.biggus.system_4 I/时间线:时间线:Activity_idle id:android.os.BinderProxy@346384f1 time:13135175 06-17 16:34:37.870 11800-11800/com.example.biggus.system_4 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN 06-17 16:34:40.740 11800-11800/com.example.biggus.system_4 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN 06-17 16:34:43.850 11800-11800/com.example.biggus.system_4 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN 06-17 16:34:43.930 11800-11800/com.example.biggus.system_4 I/时间线:时间线:Activity_launch_request id:com.example.biggus.system_4 time:13143016 06-17 16:34:44.060 11800-11800/com.example.biggus.system_4 I/System.out: Providergpshas 已被选择 06-17 16:34:44.070 11800-11800/com.example.biggus.system_4 D/AndroidRuntime: 关闭虚拟机 06-17 16:34:44.070 11800-11800/com.example.biggus.system_4 E/AndroidRuntime:致命异常:主要 进程:com.example.biggus.system_4,PID:11800 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.biggus.system_4/com.example.biggus.system_4.Location_Informaion}:java.lang.NullPointerException:尝试调用虚拟方法'void com.example.biggus。 system_4.Location_Informaion$ConnectedThread.write(java.lang.String)' 在空对象引用上 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) 在 android.app.ActivityThread.access$900(ActivityThread.java:172) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:145) 在 android.app.ActivityThread.main(ActivityThread.java:5834) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void com.example.biggus.system_4.Location_Informaion$ConnectedThread.write(java.lang.String)' 在 com.example.biggus.system_4.Location_Informaion.onLocationChanged(Location_Informaion.java:283) 在 com.example.biggus.system_4.Location_Informaion.onCreate(Location_Informaion.java:89) 在 android.app.Activity.performCreate(Activity.java:6221) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) 在 android.app.ActivityThread.access$900(ActivityThread.java:172) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:145) 在 android.app.ActivityThread.main(ActivityThread.java:5834) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

【问题讨论】:

    标签: android bluetooth arduino communication


    【解决方案1】:

    在处理程序中使用它之前,您没有初始化 txtArduino:

    txtArduino.setText("Data from Arduino: " + sbprint);  
    

    【讨论】:

      【解决方案2】:

      错误在 txtArduino.setText("Data from Arduino: " + sbprint);

      您尚未使用相应的 textview 初始化 txtArduino 对象。请执行 findviewByid 并将相应的 textview 放入 txtArduino 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多