Android 如何防止在数据库中添加重复的电话联系人?

Android 如何防止在数据库中添加重复的电话联系人?,android,arrays,database,sqlite,android-contacts,Android,Arrays,Database,Sqlite,Android Contacts,在我的Android应用程序中,我有一个电话联系人列表。我想通过选择复选框和onbutton单击,将这些联系人添加到私人列表中。这里我想要的是,若数据库中已经存在联系人,那个么就不应该添加他们。我怎样才能做到?请帮忙 代码如下: private MyListAdapter adapter; ArrayList<String> item_id = new ArrayList<String>(); ArrayList<String> item_contact_na

在我的Android应用程序中,我有一个电话联系人列表。我想通过选择
复选框
和onbutton单击,将这些联系人添加到私人列表中。这里我想要的是,若数据库中已经存在联系人,那个么就不应该添加他们。我怎样才能做到?请帮忙

代码如下:

private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_contact_name = new ArrayList<String>();
ArrayList<String> filteredList = new ArrayList<String>();
ArrayList<String> item_contact_number = new ArrayList<String>();
Uri queryUri;
boolean flag = false;
boolean[] selection;
static ArrayList<String> selection_val;
private Button btn_select, btn_remove;
DbManager manager;
String[] contactArray;
Cursor Cursor, cursor1;
public static String[] selectedData;
String phoneNumber;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_contacts);
    manager = new DbManager(this);   
    try{
        queryUri = ContactsContract.Contacts.CONTENT_URI;

        //String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
        Cursor Cursor = getContentResolver().query
                (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        showEvents(Cursor);


        cursor1 = manager.Return_All_Contacts();
        contactArray = showEvents2(cursor1);
        //final ViewHolder holder = new ViewHolder();
        selection = new boolean[item_id.size()];
        selection_val = new ArrayList<String>();
        selectedData=new String[selection.length];

        adapter = new MyListAdapter(this);
        setListAdapter(adapter);

        btn_select = (Button) findViewById(R.id.button1);
        btn_select.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                int len = selection.length;
                int cnt = 0;
                String selectIds = "";
                for (int i = 0; i < len; i++) {
                    if (selection[i]) {

                        cnt++;
                    }
                }

                for (int i = 0; i < selection_val.size(); i++) {
                    //                  selectedData[i]=item_msg_body.get(i);
                    selectedData[i]=selection_val.get(i);
                    selectIds = selectIds + " | " + selection_val.get(i);
                }
                try{

                    addContacts(selectedData);
                }
                catch(Exception ex)
                {
                    Log.e("ERROR", ex.toString());
                }
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Your have  Selected   " + cnt + " ids. " + " "+ selectIds, Toast.LENGTH_LONG).show();
                }
            }


        });
    }
    catch(Exception ex)
    {
        Log.e("Error in retrieving phone", ex.toString());
    }

    btn_remove = (Button)findViewById(R.id.remove);
    btn_remove.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
             int len = selection.length;
                int cnt = 0;
                String selectIds = "";
                for (int i = 0; i < len; i++) {
                    if (selection[i]) {

                        cnt++;
                    }
                }

                for (int i = 0; i < selection_val.size(); i++) {
                selectedData[i]=selection_val.get(i);
                    selectIds = selectIds + " | " + selection_val.get(i);
                }
                deleteMultiple(selectedData);
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
                } else {
         }
            }

        });
}


public class MyListAdapter extends BaseAdapter{
    Context con;
    private LayoutInflater layoutinf;
    ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
    ArrayList<String> items_ = new ArrayList<String>();

    public MyListAdapter(
            privateContacts sample_MultipleSelectionActivity) {
        con = sample_MultipleSelectionActivity;
    }

    public int getCount() {
        return item_id.size();
    }

    public Object getItem(int position) {
        return item_id.size();
    }

    public long getItemId(int position) {
        return item_id.get(position).hashCode();
    }

    public View getView(final int position, View convertView, ViewGroup arg2) {

        View v = convertView;
        ViewHolder holder = null;
        if (v == null) {
            layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutinf.inflate(R.layout.row_add_contacts, null);
            holder = new ViewHolder();
            holder.chk = (CheckBox) v.findViewById(R.id.checkBox);
            holder.tv_contact_name = (TextView) v.findViewById(R.id.tvname);
            holder.tv_number = (TextView) v.findViewById(R.id.tvphone);
            holder.iv_contact = (ImageView) v.findViewById(R.id.iv_contacts);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        holder.chk.setId(position);
        holder.tv_contact_name.setId(position);

        holder.chk.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                try {
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    String val = cb.getText().toString();
                    if (selection[id]) {
                        cb.setChecked(false);
                        selection[id] = false;
                        selection_val.remove("" + item_contact_name.get(id));
                    } else {
                        cb.setChecked(true);
                        selection[id] = true;
                        selection_val.add("" + item_contact_name.get(id));
                    }
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    Log.e("error", "" + e.toString());
                }
            }
        });
        holder.chk.setChecked(selection[position]);

        if(selection[position] == true)
        {
            //holder.tv_contact_name.setBackgroundColor(Color.GRAY);

        }
        else
        {
            holder.tv_contact_name.setBackgroundColor(Color.TRANSPARENT);

        }

        //            for(int i=0;i<contactArray.length;i++){
        //            
        //              holder.tv_contact_name.setBackgroundColor(Color.GREEN);
        //            }

        //holder.chk.setText(item_id.get(position));
        holder.tv_contact_name.setText("" + item_contact_name.get(position));
        holder.tv_number.setText("" + item_contact_number.get(position));

        return v;
    }
}

public class ViewHolder {
    private CheckBox chk;
    private TextView tv_contact_name;
    private TextView tv_number;
    private ImageView iv_contact;

}

private void addContacts(final String[] selectedItems) {
    try{

                        manager.open();
                        manager.Insert_phone_contact(selectedItems);
                        manager.close();
                        moveToLogActivity();            

    }
    catch(Exception ex)
    {
        Log.e("ERROR", ex.toString());
    }
}

private void showEvents(Cursor cursor) {

    item_id = new ArrayList<String>(cursor.getCount());
    item_contact_name = new ArrayList<String>(cursor.getCount());
    item_contact_number = new ArrayList<String>(cursor.getCount());
    //String ContactNames[] = new String[cursor.getCount()];
    String id[]=new String[cursor.getCount()];
    int i=0;
    while (cursor.moveToNext()) {

        item_contact_name.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
        item_contact_number.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
        i++;
    }


}

private String[] showEvents2(Cursor cursor) {

    String addedContacts[]=new String[cursor.getCount()];

    int i=0;
    while (cursor.moveToNext()) {
        addedContacts[i] = cursor.getString(1);
        i++;
    }

    return addedContacts;

}
@Override
public void onBackPressed() {
    Intent i = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(i);
    finish();
}
private void moveToLogActivity() {
    Intent i = new Intent(this, LogActivity.class); 
       startActivity(i);
       finish();

}


  private void deleteMultiple(String[]selectedItems) {
        manager.deleteContactsMultiselected(selectedItems);
        moveToLogActivity();    
    }
public void Insert_phone_contact(String [] contact){
    try{

        SQLiteDatabase DB = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        for(int i=0;i<contact.length;i++){
           // put all values in  ContentValues
            if (contact[i] !=null){
            cv.put(CONTACT_NAME, ""+contact[i]);

            DB.insert(TABLE_CONTACTS, null, cv); 
            }// insert in db
        }

        DB.close();  // call close
        }
    catch(Exception ex){
        Log.e("Error in phone contact insertion", ex.toString());
    }

}

您的表中是否有任何主键或唯一键约束?否,请检查编辑的帖子,我在其中也添加了表的代码
    // define table name
public static final String TABLE_CONTACTS = "CONTACTS_TABLE";
//define column of TABLE_CONTACTS
public static final String KEY_CONTACTID = "_id";
public static final String CONTACT_NAME = "Contact_name";