2013-11-01 28 views
0

首先對不起我的英語是一件壞事。 現在我正在編寫一個應用程序,並且列表中存在問題。 我總是在我的名單重複搜索設備後,當我再次搜索,我再次得到相同的設備。我必須嘗試使用​​套,但我仍然重複。 我不知道如何解決這個問題。 請用代碼幫助別人。 謝謝提前。重複在ListView藍牙

這裏是我的代碼:

`

public void Init(){ 
    foundDevicesSet = new HashSet<String>(); 
    tBtn = (ToggleButton)findViewById(R.id.toggleButton1); 
    availableDivce = (TextView)findViewById(R.id.textView2);  
    bluetoohOff =(TextView)findViewById(R.id.textView1);   
    DeviceList = (ListView)findViewById(R.id.listView1);  
    searchButton =(Button)findViewById(R.id.button1);   
    deviceNameAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1);   
    DeviceList.setAdapter(deviceNameAdapter); 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(receiver, filter); 
    receiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      // TODO Auto-generated method stub 

      String action = intent.getAction();    

      if (BluetoothDevice.ACTION_FOUND.equals(action)) {         
      BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);      
      if (newDevice.getBondState() != BluetoothDevice.BOND_BONDED) {      
       foundDevicesSet.add(newDevice.getName() + "|" + newDevice.getAddress());       

       for(String one : foundDevicesSet){      
       deviceNameAdapter.add(one); 
       } 


       }        
       } 
       }  
    };  



} ` 

回答

0

每次找到新設備後,你將再次被設置爲適配器整個設備的時間。所以,無論是:

  • 呼叫deviceNameAdapter.add(newDevice.getName() + "|" + newDevice.getAddress());,而不是將它添加到組。
  • 呼叫deviceNameAdapter.clear()將整套的適配器之前。
1

我也在藍牙項目上,5分鐘前我面對同樣的問題,而不是配對的設備,但有可用的設備。這裏是使它在沒有任何重複設備的情況下工作的代碼。我必須說,我用一個ListView顯示他們和ArrayAdapter藏漢:

if (mNewDevicesArrayAdapter.getPosition((device.getName()+ "\n" + device.getAddress())) == -1) 
{ 
    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
    mNewDevicesArrayAdapter.notifyDataSetChanged();     
} 

該指令查找此device.getName() + "\n" + device.getAddress()在一個ArrayAdapter,因爲這是我用來保存格式希望它可以幫助你。

+0

不是一個真正的通用解決方案,但+1,很好的答案 – avalancha