SQLite数据库ListView重复记录

时间:2014-05-04 16:47:58

标签: android sqlite

我有一个sqlite数据库,允许我存储联系人并将它们显示在列表视图中,但是每次我返回到android菜单并重新打开应用程序时,记录数量都会重复。我已经缩小到导致问题的代码段,但是我不知道如何停止列表视图添加新记录,同时确保它显示以前的记录。

数据库处理程序段:

public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();

                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                contact.setEmail(cursor.getString(3));
                contact.setPostcode(cursor.getString(4));
                contact.setDateOfBirth(cursor.getString(5));
                contact.setAdditionalInformation(cursor.getString(6));
                // Causes the problem yet if removed does not display a list at all
                String name = cursor.getString(1) +"\n"+ cursor.getString(2) +"\n"+ cursor.getString(3)
                              +"\n"+ cursor.getString(4) +"\n"+ cursor.getString(5) +"\n"+ cursor.getString(6);
                MainActivity.contactList.add(name);

                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

主要方法:(在oncreate中调用)

public void fillContactsList(){

        db.getAllContacts();

        listView = (ListView) findViewById(R.id.listView1);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, contactList);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                contactsView();
                Toast.makeText(getApplicationContext(), ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }           
        });     
    }

有没有人知道一种简单的方法来停止递增而不停止diplaying列表视图。感谢

0 个答案:

没有答案