【发布时间】:2016-03-21 23:46:36
【问题描述】:
我最近开始使用 Android 和 Java 进行编程,所以请多多包涵。
我编写了一个循环,在将新姓名和电话号码添加到列表和隐藏数组之前,应该删除之前找到的所有重复项。使用当前方法,我仍然会不断重复,当单击按钮再次添加所有相同的联系人时,我会再次获得所有联系人。这让我觉得重复检查方法根本无法正常工作,但我没有得到任何帮助
我有两个在外面创建的列表数组:
List<String> phnnumbers = new ArrayList<String>();
List<String> names = new ArrayList<String>();
这是添加联系人方法:
public void AddAllContacts(View view) {
try {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String linesp = System.getProperty("line.separator");
TextView quantityTextView = (TextView) findViewById(R.id.numbersview);
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
duplicatecheck(name, phoneNumber);
addthistothelist(name, phoneNumber);
}
phones.close();
}
catch (Exception e){
e.printStackTrace();
}
}
这是重复检查方法:
public void duplicatecheck(String name,String phoneNumber) {
for (int i=0;i<phnnumbers.size();i++) {
String thenumber = phnnumbers.get(i);
String thename= names.get(i);
if(thenumber.equals(phoneNumber)) {
phnnumbers.remove(i);
names.remove(i);
TextView quantityTextView = (TextView) findViewById(R.id.numbersview);
String textpost = quantityTextView.getText().toString();
String newtextpost = textpost.replaceAll(thenumber, "UNBELIEVABLEEE");
String secondtextpost = newtextpost.replaceAll(thename, "UNBELIEVABLE");
quantityTextView.setText(secondtextpost);
NumberOfContactsAdded--;
}
}
}
这是在检查重复并删除后被调用的方法,下一个方法是下一个添加数字和名称的方法:
public void addthistothelist(String nameofperson,String NumberOfPerson) {
String linesp = System.getProperty("line.separator");
TextView quantityTextView = (TextView) findViewById(R.id.numbersview);
String textpost = quantityTextView.getText().toString();
NumberOfPerson = NumberOfPerson.replaceAll("[^0-9]", "");
if(NumberOfPerson.contains("+1")) {
phnnumbers.add(NumberOfPerson);
names.add(nameofperson);
NumberOfContactsAdded++;
quantityTextView.append(linesp+nameofperson+" " +NumberOfPerson);
} else {
NumberOfPerson= "+1"+NumberOfPerson;
phnnumbers.add(NumberOfPerson);
names.add(nameofperson);
NumberOfContactsAdded++;
quantityTextView.append(linesp+nameofperson+" " +NumberOfPerson);
}
}
我真的不知道我可能做错了什么。我会尝试清理此代码,但它甚至无法正常工作。
【问题讨论】:
标签: java android loops arraylist duplicates