如何在Sqlite数据库中添加所有手机通讯录?

时间:2014-04-22 10:03:40

标签: android sqlite contacts android-cursor

在我的Android应用中,我正在通过光标检索手机通讯录。然后我想在数据库中添加所有这些联系人,如下所示:

    public class SettingsActivity extends Activity  {
    ToggleButton tb_hide;
    ToggleButton tb_unhide;
    TextView tv_add_contacts;
    TextView tv_restore_contacts;
    DbManager manager;
    Context context;
    String[] privateContacts;
    Uri queryUri;
    String selectIds = "";
    String ContactId[];
    String ContactNames[];
    String ContactNumbers[];
    public static String[] wholContactData;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        try{
            context = this;
            findView();
            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);
            privateContacts=showEvents(Cursor);
            wholContactData=new String[privateContacts.length];
            tv_add_contacts.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v) {
                    addcontacts();
                }
            });
            tv_restore_contacts.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v) {


                    for(int i=0;i<privateContacts.length;i++){
                        selectIds = selectIds + " | " + privateContacts[i];
                        wholContactData[i]=privateContacts[i];
                    }
                    try{
                        addAllContacts(wholContactData);
                    }
                    catch(Exception ex)
                    {
                        Log.e("ERROR in adding all contacts", ex.toString());
                    }

                    Toast.makeText(getApplicationContext(),""+selectIds, 3000).show();

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


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

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

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




    protected String[] showEvents(Cursor cursor) {
        ContactId= new String[cursor.getCount()];
        ContactNames = new String[cursor.getCount()];
        ContactNumbers = new String[cursor.getCount()];
        int i=0;
        while (cursor.moveToNext()) {
            ContactId[i] = i+"";
            ContactNames[i] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            ContactNumbers[i] = Util.getContactNumber(ContactNames[i], context);
            i++;

        }

        return ContactNames;
    }


    private void findView() {
        TextView tv_hide = (TextView)findViewById(R.id.tv_hide);
        TextView tv_hide_desc = (TextView)findViewById(R.id.tv_hide_desc);

        tv_add_contacts = (TextView)findViewById(R.id.tv_add_contacts);
        TextView tv_add_contacts_desc = (TextView)findViewById(R.id.tv_add_contacts_desc);
        tv_restore_contacts = (TextView)findViewById(R.id.Tv_restore_contacts);
        TextView tv_restore_contacts_desc = (TextView)findViewById(R.id.tv_restore_contacts_desc);

        tb_hide = (ToggleButton)findViewById(R.id.tb_hide);
        tb_hide.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                HideUnhideIcon();
            }});


    }
    private void HideUnhideIcon() {
        if(tb_hide.isChecked()){
            PackageManager pm = getPackageManager();
            ComponentName com_name = new ComponentName("com.android.discrete.main",
                    "com.android.discrete.main.SplashScreen");
            pm.setComponentEnabledSetting(com_name, 
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
            Toast.makeText(getApplicationContext(), "Your app is hidden now, Dial provided security code  to get into discrete app.", 3000).show();
        }
        else if(tb_hide.isChecked()==false){
            PackageManager pm = getPackageManager();
            ComponentName com_name = new ComponentName("com.android.discrete.main",
                    "com.android.discrete.main.SplashScreen");
            pm.setComponentEnabledSetting(com_name, 
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                    ,
                    PackageManager.DONT_KILL_APP );

        }


    }

    private void addcontacts() {
        final ProgressDialog myPd_ring=ProgressDialog.show(this, "Phone Contacts", "Loading please wait..", true);
        myPd_ring.setCancelable(true);
        new Thread(new Runnable() {  
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try
                {
                    movetoPrivateContacts();
                }catch(Exception e){}
                myPd_ring.dismiss();
            }

        }).start();                                          
    }
    private void moveToLogActivity() {
        Intent i = new Intent(this, LogActivity.class); 
        startActivity(i);
        finish();

    }


    private void movetoPrivateContacts() {
        Intent intent = new Intent(this,privateContacts.class);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);

    }
}

数据库代码如下:

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());
    }

}

我想在点击“tv_restore_contacts”时将所有联系人添加到数据库。但是我得到了NullPointerException。我不知道我哪里错了? logcat错误堆栈为java.lang.NullPointerException

1 个答案:

答案 0 :(得分:1)

使用以下代码获取联系人&amp;将它们返回到list数据类型以将它们整个列表保存在db中或在方法内部打开数据库连接,并对要存储的每个联系对象执行sql insert语句。 N / B不推荐使用Contacts API,请务必使用ContactsContract Api。

Private void getDetails(){
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
    String[] projection    = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER };
    Cursor names = getContentResolver().query(uri, projection, null, null, null);
    int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    names.moveToFirst();
    do {
       String name   = names.getString(indexName);
       Log.e("Name new:", name);
       String number = names.getString(indexNumber);
       Log.e("Number new:","::"+number);
    } while (names.moveToNext());
}