从电话联系人列表中检索联系人

时间:2014-03-07 18:12:18

标签: java android sqlite

我正在尝试从手机的联系人列表中获取所有联系人,并将其存储到我自己的数据库中。我遵循了一些教程,但不幸的是我的应用程序不会在textview中显示联系人。我创建了databasehelper类来为联系人创建表,我正在尝试获取手机联系并将它们存储在该表中。另外我想在textView中显示联系人。我还想添加按钮来添加新的联系人。

这是我的ContacFragment类:

public class ContactFragment extends ListFragment {

        public static final String TAG = "ContactManager";
        private Button AddAccountButton;


    public ContactFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, container,
                false);

            TextView textView = null;
            textView = (TextView) view.findViewById(R.id.contact_text_view);
            Cursor c = getContacts();
            textView.setText(c.getString(1));

            AddAccountButton = (Button)view.findViewById(R.id.addContactButton);

            AddAccountButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Log.d(TAG, "mAddAccountButton clicked");
               //     launchContactAdder();
                }
            });

            // Populate the contact list
            populateContactList();

        return view;
    }


    private void populateContactList() {
        // Build adapter with contact entries
        Cursor cursor = getContacts();
        String[] fields = new String[] {
            ContactsContract.Data.DISPLAY_NAME
    };


}
    private Cursor getContacts()
    {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        ContentResolver contentResolver= this.getActivity().getContentResolver();
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };

        Log.i("CONTACTS", "after_String");

        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        Cursor c = contentResolver.query(uri, projection,null,selectionArgs, sortOrder);
        Log.i("CONTACTS", Integer.toString(c.getColumnCount()));
        Log.i("CONTACTS", Integer.toString(c.getColumnIndex("KEY_CONTACT_ID")));
        Log.i("CONTACTS", Integer.toString(c.getColumnIndex("KEY_NAME")));
        Log.i("CONTACTS", Integer.toString(c.getColumnIndex("KEY_PHONE_NO")));
        //Log.i("CONTACTS", c.getString(2));
        return c;
    }


//  protected void launchContactAdder() {
//        Intent i = new Intent(AddContact.class);
//        startActivity(i);
//    }
}

数据库helper.java

@Override
    public void onCreate(SQLiteDatabase db) {
//craete the contact table
         sql = "CREATE TABLE " + TABLE_CONTACTS + "("
                    + KEY_CONTACT_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                    + KEY_PHONE_NO + " TEXT" + ")";
            db.execSQL(sql);


        insertInitialProjects(db);
    }

// Adding new contact
    public void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_CONTACT_ID, contact.getContactName()); // Contact Id
        values.put(KEY_NAME, contact.getContactName()); // Contact Name
        values.put(KEY_PHONE_NO, contact.getPhoneNumber()); // Contact Phone


        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting All Contacts
    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.setContactId(Integer.parseInt(cursor.getString(0)));
                contact.setContactName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PHONE_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }

    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getContactName());
        values.put(KEY_PHONE_NO, contact.getPhoneNumber());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getContactId()) });
    }

    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getContactId()) });
        db.close();
    }


    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

一旦我打开联系人片段应用程序崩溃

logcat的

03-07 18:11:28.055: W/dalvikvm(13225): threadid=1: thread exiting with uncaught exception (group=0x415e7ba8)
03-07 18:11:28.075: E/AndroidRuntime(13225): FATAL EXCEPTION: main
03-07 18:11:28.075: E/AndroidRuntime(13225): Process: com.projecttracker, PID: 13225
03-07 18:11:28.075: E/AndroidRuntime(13225): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 40
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.database.CursorWrapper.getString(CursorWrapper.java:114)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at com.projecttracker.ContactFragment.onCreateView(ContactFragment.java:52)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.os.Handler.handleCallback(Handler.java:733)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.os.Handler.dispatchMessage(Handler.java:95)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.os.Looper.loop(Looper.java:136)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at java.lang.reflect.Method.invokeNative(Native Method)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at java.lang.reflect.Method.invoke(Method.java:515)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-07 18:11:28.075: E/AndroidRuntime(13225):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您的错误在这里:

android.database.CursorIndexOutOfBoundsException: 
Index -1 requested, with a size of 40

在这里你关闭光标并在关闭后使用它:

  public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
  }

应该是:

  public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        int contact_count = 0;

        Cursor cursor = db.rawQuery(countQuery, null);
        if (cursor != null) {          
          contact_count = cursor.getCount();           
          cursor.close();
        }

        // return count
        return contact_count;
  }

检查: http://developer.android.com/reference/android/database/Cursor.html#close%28%29