2013-11-01 43 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