我从服务器获得一个JSON Array
,其中包含使用我的应用程序的人的手机上的一些电话联系人。我希望这些电话号码以ListView
显示给用户,'Already a contact'
。
称为JsonArrayMatchingContacts
的JSON Array
可能是,例如:
[{"contact_phonenumber":"+12345678"},{"contact_phonenumber":"+23456789},
{"contact_phonenumber":"+34567890"}]
这是我的代码,但它不起作用。它适用于单个值 - 例如,如果我有if (phoneNumberofContact.equals("+12345678")) etc..
它就会提出Already a Contact
但我需要让它为我的JSON Array
工作。你能帮忙吗?
SelectPhoneContact selectContact = new SelectPhoneContact();
ArrayList<String> MatchingContacts = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(JsonArrayMatchingContacts);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingContacts.add(obj.getString("contact_phonenumber"));
}
} catch(Exception e) {
e.printStackTrace();
}
if (phoneNumberofContact.equals(MatchingContacts))
{
phoneNumberofContact= "Already a contact";
selectPhoneContacts.add(selectContact);
} else {
selectPhoneContacts.add(selectContact);
}
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);
您正在比较字符串 ( phoneNumberofContact ( 和列表 ( MatchingContacts(。
您应该检查字符串是否包含在列表中。
if (MatchingContacts.contains( phoneNumberofContact )) {
put your if condition in loop..you will get it.try this
SelectPhoneContact selectContact = new SelectPhoneContact();
ArrayList<String> MatchingContacts = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(JsonArrayMatchingContacts);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
if (phoneNumberofContact.equals(MatchingContacts))
{
phoneNumberofContact= "Already a contact";
selectPhoneContacts.add(selectContact);
} else {
selectPhoneContacts.add(selectContact);
}
}
} catch(Exception e) {
e.printStackTrace();
}
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);