ArrayList仅存储最后读取的值

时间:2014-11-10 21:21:16

标签: java android arraylist

我正在尝试从我的Android手机中读取联系人以修改它们并将它们写回数据库。  到目前为止,该项目有三个班级:

  • MainActivity.java。这是我读取数据库的地方,填充我创建的联系人对象并将它们放在列表中。

    public class MainActivity extends Activity {
    private ArrayAdapter<String> adapter;
    
    // Store contacts values in these arraylist.
    // I t is not really needed for this implementation but I keep this just in case
    
    public static ArrayList<String> phoneValueArr = new ArrayList<>();
    public static ArrayList<String> nameValueArr = new ArrayList<>();
    
    // Store the values of names and associated phone numbers.
    public  ContactData contactsData= new ContactData(); 
    
    // List to store the contacts
    public  ContactsDataList contactsList= new ContactsDataList();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    adapter = new ArrayAdapter<>
    (this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
    readContactsData();
    
    //Display the number of contacts
    Toast.makeText(getApplicationContext(),
            "read " + phoneValueArr.size() + " contacts. "  , Toast.LENGTH_LONG).show();
    
    
    pressButton();
    
        for(ContactData c:contactsList.getContacts()){
            Toast.makeText(getApplicationContext(),
                    c.getContact_name() + "Hopes   on God "  ,    Toast.LENGTH_LONG).show();
    
        }
    
    }
    }
    
    public  void readContactsData() {
    
    try {
    
        // Reading Contacts Name And Number
    
        String phoneNumber = "";
        ContentResolver cr = getBaseContext().getContentResolver();
    
        // Query to get contact name
    
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
    
        // If data data found in contacts
        if (cur.getCount() > 0) {
    
         Log.i("AutocompleteContacts", "Reading   contacts........");
    
         int k = 0;
         String name = "";
    
         //Until there are no more contacts stored
          while (cur.moveToNext()) {
    
          String id = cur.getString(cur
          .getColumnIndex(ContactsContract.Contacts._ID));
          name = cur
          .getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    
                // Check contact have phone number
                if (Integer
                        .parseInt(cur.getString(cur
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
    
                    // Create query to get phone number by contact id
                    Cursor pCur = cr
                    .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                    + " = ?", new String[] { id },
                    null);
                    int j = 0;
    
                    //Until query is stopped
                    while (pCur.moveToNext()) {
                        // Sometimes get multiple data
                        if (j == 0) {
                            // Get Phone number
                            phoneNumber = ""
                                    + pCur.getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
                            // Add contacts names to adapter
                            adapter.add(name);
    
                            // Add ArrayList names to adapter
                            phoneValueArr.add(phoneNumber.toString());
                            nameValueArr.add(name.toString());
    
                            // Set contact name and phone number
                            // i.e parse the SQLlite query to set the POJO's
                            contactsData.setPhone_number(phoneNumber.toString());
                            contactsData.setContact_name(name.toString());
    
    
                            // Add Contacts to list
                            contactsList.addContact(contactsData);
    
    
                          j++;
                            k++;
                        }
    
                    } // End while loop
    
                    pCur.close();
                } // End if
    
            }// End while loop
    
        } // End Cursor value check
        cur.close();
    
    } catch (Exception e) {
        Log.i("AutocompleteContacts", "Exception : " + e);
    }
    }
    
  • ContactData类,我在其中创建实例化对象的类。

    public class ContactData {
    
    public String contact_name;
    public String phone_number;
    
    public ContactData(){
    
    }
    
    public  ContactData(String contact_name, String phone_number) {
    
    this.contact_name=contact_name;
    this.phone_number=phone_number;
    }
    
    
    
    public String getContact_name() {
    return contact_name;
    }
    
    public void setContact_name(String contact_name) {
    this.contact_name = contact_name;
    }
    public String getPhone_number() {
    return phone_number;
    }
    public void setPhone_number(String phone_number) {
    this.phone_number = phone_number;
    }
    
     public String toString() {
        return contact_name + ", " + phone_number;
    }
    
    
    public boolean equals(Object obj) {
    if (obj instanceof ContactData) {
        ContactData contact = (ContactData) obj;
        return (contact_name.equals(contact.getContact_name()) && phone_number
                .equals(contact.getPhone_number()));
    }
    
    return false;
    }
    
    
    public int hashCode() {
        return (contact_name.length() + phone_number.length());
    }
     class ContactNameComparator implements Comparator<ContactData> {
        public int compare(ContactData contact1, ContactData contact2) {
            return   contact1.getContact_name().compareToIgnoreCase(contact2.getContact_name());
        }
     }
     }
    
  • ContactsDataList,它接收对象并存储它们。

     public class ContactsDataList  {
    
    
    
     public List<ContactData> contactList;
    
    public ContactsDataList() {
    
    this(new ArrayList<ContactData>());
    }
    
    public ContactsDataList(List<ContactData> contactList) {
    this.contactList = contactList;
    }
    
    public void addContact(ContactData contact) {
    if (contactList != null) {
            contactList.add(contact);
        }
    }
    
    public List<ContactData> getContacts() {
    return contactList;
    }
    
    public void setContacts(List<ContactData> contacts) {
    this.contactList = contacts;
    }
    
    
    }
    

我列表中的联系人对象都是一样的,我没看到出错的地方,因为arraylists phoneValuerArr和nameValueArr都有正确的数据。

ContactsDataList,contactList,仅包含最后一次阅读的联系人。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

您在ContactData循环的每次迭代中重用while的相同实例,只是更新其属性。您需要为每次迭代创建一个单独的实例

while (pCur.moveToNext()) {
    ...
    ContactData contactsData = new ContactData();
    contactsData.setPhoneNumber(...);
    ...
}