2017-01-05 4 views
0

Android Bluetooth App stürzt auf einen Klick, ich habe das Problem gegoogled, aber dint bekommen die entsprechende Antwort. Bitte hilf mir, dass ich neu bei Android bin. Ich erstelle eine Bluetooth-App mit dem Android-Studio, es stürzt ab, wenn ich auf die Schaltfläche zum Verbinden des Geräts klicke. unten ist der Code, in dem ich denke, der Fehler ist.Android Bluetooth App stürzt auf Knopfdruck

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

Haben Sie Ihr Bluetooth geöffnet? – Hoo

+0

Ich benutze Android Studio dafür und im Emulator bekomme ich den Fehler .. und auch auf dem Gerät. –

+0

Mögliches Duplikat von [Was ist eine NullPointerException, und wie behebe ich es?] (Http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –

Antwort

1

Versuch zu prüfen, ob BluetoothAdapter vor dem Aufruf getBondedDevices null ist, weil es null zurück, wenn Bluetooth auf Ihrem Gerät nicht unterstützt. Laut Ihrem Kommentar in Ihrer Frage wird Bluetooth auf Android Emulator nicht unterstützt. Bitte überprüfen Sie es in documentation.

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

Überprüfen Sie es wie folgt:

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

Hoffe, dass es für Sie hilfreich sein.

+0

Ich benutzte Ihren Code und jetzt bekomme ich Fehler 'Fehler: (238, 43) Fehler: kann Symbolvariable nicht finden pairedDevices' –

+0

Vielleicht greifen Sie auf' pairedDevices' Variable von außerhalb der Prüfung 'mBtAdapter' Bedingung. Wenn Sie es außerhalb der Bedingung verwenden möchten, müssen Sie es als globale Variable deklarieren. –

+0

'Set pairedDevices = null; if (mBtAdapter! = Null && mBtAdapter.isEnabled()) { // Erledige deine Aufgabe pairedDevices = mBtAdapter.getBondedDevices(); } else { Toast.makeText (DeviceActivity.this, "Bluetooth wird auf Ihrer Hardware nicht unterstützt", Toast.LENGTH_SHORT) .show(); } '** ist es richtig? ** –