我毫不怀疑contains()方法工作正常,但显然我做错了。我正在开发一个Android应用程序,我正在检测WiFi并在listView中列出WiFi。我试图过滤掉同一个访问点的重复出现,所以我创建一个数组来跟踪重复项。这是我的代码:
function doSomething(){
... execute code here ...
}
// Invoke function
doSomething();
这是apList项的内容或我调用apList.get(i)时得到的内容:
public void getWifi(){
ListView wifiList = (ListView)findViewById(R.id.listView);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
List<ScanResult> apList = wifiManager.getScanResults();
wifiManager.startScan();
List<String> wifees = new ArrayList<>();
//split info into arrays
for(int i=0; i < apList.size(); i++){
String[] daList = String.valueOf(apList.get(i)).split(",");
String info = "";
List<String> SSIDs = new ArrayList<>();
for (String listItem : daList) {
String topic = String.valueOf(listItem.split(":")[0]);
String val = listItem.split(":")[1];
Log.d(TAG, topic);
if (Objects.equals(topic, "SSID")) {
if(SSIDs.contains(val)){
Log.d(TAG, "CONTAINS");
break;
} else {
SSIDs.add(val);
info = val;
}
} else if (Objects.equals(topic, " level")){
String strength = "";
if (Integer.parseInt(val.substring(1)) >= -35) {
strength = "100%";
} else if (Integer.parseInt(val.substring(1)) <= -35 && Integer.parseInt(val.substring(1)) >= -65) {
strength = "50%";
} else {
strength = "1%";
}
info += " " + strength;
}
}
wifees.add(info);
}
assert wifiList != null;
ArrayAdapter apter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, wifees);
wifiList.setAdapter(apter);
}
以下是该代码的输出(大致是因为它是在手机上,出于安全原因我宁愿不包括AP名称):
SSID: SCHOOL-GUEST, BSSID: 04:04:04:04:04:04, capabilities: [ESS], level: -91, frequency: 2412, timestamp: 72500687089, distance: ?(cm), distanceSd: ?(cm), passpoint: no, ChannelBandwidth: 0, centerFreq0: 0, centerFreq1: 0, 80211mcResponder: is not supported
如果我能得到第二个意见,那就太好了。我觉得我错过了一些明显的东西。谢谢!
答案 0 :(得分:2)
.contains
无效,因为您在List<String> SSIDs = new ArrayList<>();
内致电for(int i=0; i < apList.size(); i++){
。您基本上为每个循环迭代创建新的空List。你应该在外部for循环中调用它一次:
List<String> SSIDs = new ArrayList<>();
for(int i=0; i < apList.size(); i++){
...
}