2017-01-05 180 views
0

安卓藍牙應用程序崩潰點擊一個按鈕,我GOOGLE了這個問題,但力量得到相關的答案。請幫助我是Android新手。 我正在使用android工作室創建一個藍牙應用程序,只要點擊連接設備按鈕,它就會崩潰。下面是我認爲錯誤的代碼。安卓藍牙應用程序崩潰按一下按鈕

DeviceActivity.java

package com.contec.activity; 

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

import com.contec.spmw.R; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemClickListener; 

public class DeviceActivity extends Activity { 
    /** Called when the activity is first created. */ 

    private ListView mListView; 
    private ArrayList<SiriListItem> list; 
    private Button seachButton, serviceButton; 
    ChatListAdapter mAdapter; 
    Context mContext; 
    private String mstraddress = ""; 


    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 

    @Override 
    public void onStart() { 
     super.onStart(); 
     // If BT is not on, request that it be enabled. 
     if (!mBtAdapter.isEnabled()) { 
      Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableIntent, 3); 
     } 
    } 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.devices); 
     mContext = this; 

     init(); 
    }  

    private void init() { 
     list = new ArrayList<SiriListItem>(); 
     mAdapter = new ChatListAdapter(this, list); 
     mListView = (ListView) findViewById(R.id.list); 
     mListView.setAdapter(mAdapter); 
     mListView.setFastScrollEnabled(true); 
     mListView.setOnItemClickListener(mDeviceClickListener);  

     // Register for broadcasts when discovery has finished 
     IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     this.registerReceiver(mReceiver, foundFilter); 

     // Register for broadcasts when a device is discovered 
     IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     this.registerReceiver(mReceiver, discoveryFilter); 

     // Get a set of currently paired devices 
     Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 

     // If there are paired devices, add each one to the ArrayAdapter 
     if (pairedDevices.size() > 0) { 
      for (BluetoothDevice device : pairedDevices) { 
       list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true)); 
       mAdapter.notifyDataSetChanged(); 
       mListView.setSelection(list.size() - 1); 
      } 
     } else { 
      list.add(new SiriListItem("Some CHinese Text", true)); 
      mAdapter.notifyDataSetChanged(); 
      mListView.setSelection(list.size() - 1); 
     } 

     seachButton = (Button)findViewById(R.id.start_seach); 
     seachButton.setOnClickListener(seachButtonClickListener); 

    }  
    private OnClickListener seachButtonClickListener = new OnClickListener() { 
     @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       if(mBtAdapter.isDiscovering()) 
       { 
        mBtAdapter.cancelDiscovery(); 
        //seachButton.setText("重新搜索"); 
        seachButton.setText("Re Find"); 
       } 
       else 
       { 
        list.clear(); 
        mAdapter.notifyDataSetChanged(); 

        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 
        if (pairedDevices.size() > 0) { 
          for (BluetoothDevice device : pairedDevices) { 
           list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true)); 
           mAdapter.notifyDataSetChanged(); 
           mListView.setSelection(list.size() - 1); 
          } 
        } else { 
          list.add(new SiriListItem("No devices have been paired", true)); 
          mAdapter.notifyDataSetChanged(); 
          mListView.setSelection(list.size() - 1); 
        }     

        mBtAdapter.startDiscovery(); 
        //seachButton.setText("Some Chinese Text"); 
        seachButton.setText("stop"); 
       }     
      } 
     }; 


    // The on-click listener for all devices in the ListViews 
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { 
      // Cancel discovery because it's costly and we're about to connect  

      SiriListItem item = list.get(arg2); 
      String info = item.message; 
      mstraddress = info.substring(info.length() - 17);     
     // Bluetooth.BlueToothAddress = address; 

      AlertDialog.Builder StopDialog =new AlertDialog.Builder(mContext); 
      //StopDialog.setTitle("Some CHinese Text");   
      StopDialog.setTitle("connect"); 
      StopDialog.setMessage(item.message); 
      //StopDialog.setPositiveButton("Some CHinese Text", new DialogInterface.OnClickListener() { 
      StopDialog.setPositiveButton("connect", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       // TODO Auto-generated method stub 
       mBtAdapter.cancelDiscovery(); 
       //seachButton.setText("Some Chinese Text");  
       seachButton.setText("Re find"); 

     //  Bluetooth.serviceOrCilent=ServerOrCilent.CILENT; 
     //  Bluetooth.mTabHost.setCurrentTab(1); 

       if(!mstraddress.equals("null")) 
       { 
        //device = mBtAdapter.getRemoteDevice(mstraddress); 

        //clientConnectThread = new clientThread(); 
        //clientConnectThread.start(); 

        Intent intent2 = new Intent(); 
        intent2.setClass(DeviceActivity.this, MainActivity.class); 

        Bundle bundle = new Bundle(); 
        bundle.putString("straddress", mstraddress); 
        intent2.putExtra("bundle", bundle); 

        setResult(0, intent2); 
        DeviceActivity.this.finish(); 
       } 
       else 
       { 
        Toast.makeText(DeviceActivity.this, "address is null !", Toast.LENGTH_SHORT).show(); 
       } 

      } 
      }); 
      //StopDialog.setNegativeButton("Some CHinese Text",new DialogInterface.OnClickListener() {      
      StopDialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
     //   Bluetooth.BlueToothAddress = null; 
       } 
      }); 
      StopDialog.show();        
     } 
    }; 

    private Handler LinkDetectedHandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 

      if (msg.what == 0) 
      { 
       Toast.makeText(mContext, (String)msg.obj, Toast.LENGTH_SHORT).show(); 
      } 
      else if (msg.what == 1) 
      { 
       String str = "Some chinese Text:\r\n" + (String)msg.obj; 
       Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();//測試 
      } 

     } 

    };  

    // The BroadcastReceiver that listens for discovered devices and 
    // changes the title when discovery is finished 
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 

      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) 
      { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // If it's already paired, skip it, because it's been listed already 
       if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
       { 
        list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), false)); 
        mAdapter.notifyDataSetChanged(); 
        mListView.setSelection(list.size() - 1); 
       } 
      // When discovery is finished, change the Activity title 
      } 
      else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
      { 
       setProgressBarIndeterminateVisibility(false); 
       if (mListView.getCount() == 0) 
       { 
        //list.add(new SiriListItem("Some CHinese Text", false)); 
        list.add(new SiriListItem("not find bluetooth", false)); 
        mAdapter.notifyDataSetChanged(); 
        mListView.setSelection(list.size() - 1); 
       } 
       //seachButton.setText("Some CHinese Text"); 
       seachButton.setText("Re find"); 
      } 
     } 
    }; 

    public class SiriListItem { 
     String message; 
     boolean isSiri; 
     public SiriListItem(String msg, boolean siri) { 
      message = msg; 
      isSiri = siri; 
     } 
    } 
    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 

     // Make sure we're not doing discovery anymore 
     if (mBtAdapter != null) { 
      mBtAdapter.cancelDiscovery(); 
     } 

     // Unregister broadcast listeners 
     this.unregisterReceiver(mReceiver); 
    } 
} 

logcat的

--------- beginning of crash 
E/AndroidRuntime: FATAL EXCEPTION: main 
        Process: com.contec.spmw, PID: 1937 
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contec.spmw/com.contec.activity.DeviceActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
         at android.app.ActivityThread.access$800(ActivityThread.java:144) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:135) 
         at android.app.ActivityThread.main(ActivityThread.java:5221) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at java.lang.reflect.Method.invoke(Method.java:372) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference 
         at com.contec.activity.DeviceActivity.init(DeviceActivity.java:227) 
         at com.contec.activity.DeviceActivity.onCreate(DeviceActivity.java:204) 
         at android.app.Activity.performCreate(Activity.java:5937) 
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)  
         at android.app.ActivityThread.access$800(ActivityThread.java:144)  
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)  
         at android.os.Handler.dispatchMessage(Handler.java:102)  
         at android.os.Looper.loop(Looper.java:135)  
         at android.app.ActivityThread.main(ActivityThread.java:5221)  
         at java.lang.reflect.Method.invoke(Native Method)  
         at java.lang.reflect.Method.invoke(Method.java:372)  
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)  
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)  
I/Process: Sending signal. PID: 1937 SIG: 9 
Application terminated. 
+0

你打開過藍牙了嗎? – Hoo

+0

我正在使用Android Studio,並在模擬器中出現錯誤..也在設備上。 –

+0

可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –

回答

1

嘗試查看BluetoothAdapter是否調用getBondedDevices,因爲它會返回null,如果藍牙是不是你的設備上支持前空。根據你的問題中的評論,Android模擬器不支持藍牙。請檢查它在documentation

BluetoothAdapter - the default local adapter, or null if Bluetooth is not supported on this hardware platform

檢查它如下:

if (mBtAdapter != null && mBtAdapter.isEnabled()) { 
    // do your task 
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 
} else { 
    // Bluetooth is not supported on your hardware 
} 

希望這將是對你有幫助。

+0

我用你的代碼,現在我得到錯誤'錯誤:(238,43)錯誤:找不到符號變量pairedDevices' –

+0

也許你正在訪問'mBtAdapter'條件以外的'pairedDevices'變量。如果您想從條件之外使用它,則需要將其聲明爲全局變量。 –

+0

'Set pairedDevices = null;如果(mBtAdapter!= null && mBtAdapter.isEnabled()){ //執行您的任務 pairedDevices = mBtAdapter.getBondedDevices(); Toast.makeText(DeviceActivity.this,「您的硬件不支持藍牙」,Toast.LENGTH_SHORT).show();其他{ }其他{ Toast.makeText }'**是否正確?** –

相關問題