2014-04-21 133 views
-2

我已经开始尝试学习如何在android平台上编程,并且我制作了应该与蓝牙模块进行通信的程序。但是,每次启动时,它立即崩溃,并且不幸地响应,“程序名称”已停止工作。怎么了?Android蓝牙程序立即崩溃

Main Activity 
    package com.example.enge1104; 

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

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.ActionBarActivity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends ActionBarActivity { 

    BluetoothAdapter mBluetoothAdapter; 
    BluetoothSocket mmSocket; 
    BluetoothDevice mmDevice; 
    OutputStream mmOutputStream; 
    InputStream mmInputStream; 
    TextView myLabel; 
    Button buttonLeft; 
    Button buttonRight; 




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


     buttonLeft = (Button)findViewById(R.id.buttonLeft); 
     buttonRight = (Button)findViewById(R.id.buttonRight); 
     myLabel = (TextView)findViewById(R.id.display); 


     buttonLeft.setOnTouchListener(new OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 

       switch(event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        try { 
         sendData(0); 
        } catch (IOException e) {} 
        break; 
       case MotionEvent.ACTION_UP: 
        try { 
         sendData(1); 
        } catch (IOException e) {} 
        break; 
       } 
       return false; 
      } 
     }); 

     buttonRight.setOnTouchListener(new OnTouchListener() { 

      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       switch(event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        try { 
         sendData(2); 
        } catch (IOException e) {} 
        break; 
       case MotionEvent.ACTION_UP: 
        try { 
         sendData(3); 
        } catch (IOException e) {} 
        break; 
       } 
       return false; 
      } 
     }); 



     try 
     { 
      findBT(); 
      openBT(); 
     } 
     catch (IOException ex) { } 

     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()) 
        .commit(); 
     } 

    } 


    void sendData(int newValue) throws IOException 
    { 
     mmOutputStream.write(newValue); 
    } 

    void findBT() 
    { 
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if (!mBluetoothAdapter.isEnabled()) { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBtIntent,0); 
     } 
     mmDevice = null; 
     Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
     // If there are paired devices 
     if (pairedDevices.size() > 0) { 

      for (BluetoothDevice device : pairedDevices) { 

      if(device.getName().equals("HC-06")) //Name of bluetooth module 
       { 
        mmDevice = device; 
        break; 
       } 
      } 
     } 
    } 

    void openBT() throws IOException 
    { 
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID 

     mmSocket = null;  
      mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); 
      mmSocket.connect(); 
      mmOutputStream = mmSocket.getOutputStream(); 
      myLabel.setText("Bluetooth Opened"); 
    } 


    @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 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(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      return rootView; 
     } 
    }} 

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:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.enge1104.MainActivity$PlaceholderFragment" > 

    <Button 
     android:id="@+id/buttonLeft" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerVertical="true" 
     android:layout_marginRight="46dp" 
     android:layout_toLeftOf="@+id/buttonRight" 
     android:text="@string/button_left" /> 

    <Button 
     android:id="@+id/buttonRight" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/buttonLeft" 
     android:layout_alignBottom="@+id/buttonLeft" 
     android:layout_alignParentRight="true" 
     android:layout_marginRight="67dp" 
     android:text="@string/button_right" /> 

    <TextView 
     android:id="@+id/display" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="46dp" 
     android:text="@string/disDisplay" /> 

</RelativeLayout> 

的strings.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <string name="app_name">ENGE1104</string> 
    <string name="hello_world">Hello world!</string> 
    <string name="action_settings">Settings</string> 
    <string name="button_right">Right</string> 
    <string name="button_left">Left</string> 
    <string name="disDisplay">Not Connected</string> 
</resources> 

清单

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.enge1104" 
    android:versionCode="1" 
    android:versionName="1.0" > 
    <uses-permission android:name="android.permission.BLUETOOTH" /> 
    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="19" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.example.enge1104.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

日志猫

04-21 15:36:14.572: I/Process(25563): Sending signal. PID: 25563 SIG: 9 
04-21 15:36:26.512: D/AndroidRuntime(25760): Shutting down VM 
04-21 15:36:26.512: W/dalvikvm(25760): threadid=1: thread exiting with uncaught exception (group=0x41522ba8) 
04-21 15:36:26.512: E/AndroidRuntime(25760): FATAL EXCEPTION: main 
04-21 15:36:26.512: E/AndroidRuntime(25760): Process: com.example.enge1104, PID: 25760 
04-21 15:36:26.512: E/AndroidRuntime(25760): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.enge1104/com.example.enge1104.MainActivity}: java.lang.NullPointerException 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread.access$800(ActivityThread.java:135) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.os.Handler.dispatchMessage(Handler.java:102) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.os.Looper.loop(Looper.java:136) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread.main(ActivityThread.java:5017) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at java.lang.reflect.Method.invokeNative(Native Method) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at java.lang.reflect.Method.invoke(Method.java:515) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at dalvik.system.NativeStart.main(Native Method) 
04-21 15:36:26.512: E/AndroidRuntime(25760): Caused by: java.lang.NullPointerException 
04-21 15:36:26.512: E/AndroidRuntime(25760): at com.example.enge1104.MainActivity.onCreate(MainActivity.java:51) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.Activity.performCreate(Activity.java:5231) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
04-21 15:36:26.512: E/AndroidRuntime(25760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
04-21 15:36:26.512: E/AndroidRuntime(25760): ... 11 more 
04-21 15:36:29.032: I/Process(25760): Sending signal. PID: 25760 SIG: 9 
+0

查找此处为空 - 引发异常:java.lang.NullPointerException,第51行。 – 323go

+0

空指针异常意味着我在预期对象时使用Null。我猜这意味着我的buttonLeft没有找到,因此buttonLeft =(Button)findViewById(R.id.buttonLeft); 没有达到我预期的效果。 – BillyBob

+0

正确。这是一个基本问题,你可以很好地解决那些没有使用stackoverflow的问题:)你可能想删除这个问题,因为它不会帮助任何其他人,太具体。 – 323go

回答

0

在意识到我做错了什么之后,该setContentView(R.layout.activity_main);看着所有的activity_main.xml,但我的布局实际上是在fragment_main.xml中。因此我将fragment_main.xml中的内容移至activity_main.xml。