2015-05-30 2 views
0

Я использую этот код для отображения контактов в lisview. Он отлично работает, за исключением одного. Он показывает все контакты, включая идентификатор электронной почты и другие контакты.Показать контакты в android

Я хочу показать те контакты, кто для тех, у кого есть номера телефонов. Как я могу это сделать?

Вот мой код: -

public class PhoneBookActivity extends Activity { 

     //Android listview object 
     ListView listViewPhoneBook; 

     /** Called when the activity is first created. */ 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.phone_book); 

      //get the ListView Reference from xml file 
      listViewPhoneBook=(ListView)findViewById(R.id.listPhoneBook); 

      //arrayColumns is the array which will contain all contacts name in your cursor, where the cursor will get the data from contacts database. 
      //Here we are displaying name only from the contacts database 
      String[] arrayColumns = new String[]{ContactsContract.Contacts.DISPLAY_NAME}; 
      //arrayViewID is the id of the view it will map to here textViewName only , you can add more Views as per Requirement 
      int[] arrayViewID = new int[]{R.id.textViewName}; 

     //reference to the phone contacts database using Cursor and URI in android. 
      Cursor cursor; 
     cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 

     /*Create an Adapter with arguments layoutID, Cursor, Array Of Columns, and Array of Views which is to be Populated 
     This adapter will be associated with the listview to populate items directly. So this adapter is associated with 
     the each_contact.xlm file to view in a activity */ 
     SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.each_contact, cursor, arrayColumns, arrayViewID); 
     listViewPhoneBook.setAdapter(adapter); 

     /*this is extra code for click event of any item in the list view. 
     when you will click on na contact's name in the list view. it will give you the item name and position in a listview. 
     Note that: if you want to query the contacts name details(like phone number for the clicked contact name & all details, 
     we need to query it again. i will explain it in my a separate post in my blog.*/ 

     // To handle the click on List View Item 
     listViewPhoneBook.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3) 
      { 
       // position parameter gives the index or position of ListView Item which is Clicked 
       TextView tv=(TextView)v.findViewById(R.id.textViewName); 
       String name=tv.getText().toString(); 
       Toast.makeText(getApplicationContext(), "Contact Selected: "+name, Toast.LENGTH_LONG).show(); 
      } 
     }); 

     } 
    } 

UPDATE: ---

Я решил одну из моей проблемы сам. Теперь у меня есть еще одна проблема. Как я могу позвонить по телефону по телефону, нажмите в этом списке?

Я пытаюсь сделать это:

// To handle the click on List View Item 
      listViewPhoneBook.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3) 
       { 
        // position parameter gives the index or position of ListView Item which is Clicked 
        TextView tv=(TextView)v.findViewById(R.id.textViewName); 
        String name=tv.getText().toString(); 
        Toast.makeText(getApplicationContext(), "Contact Selected: " + position, Toast.LENGTH_LONG).show(); 

        Cursor c = (Cursor) arg0.getItemAtPosition(position); 
        // Cursor c = (Cursor)arg0.getAdapter().getItem(position); 
        String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
        Toast.makeText(getApplicationContext(), "Contact Selected: " + number, Toast.LENGTH_LONG).show(); 


       } 
      }); 

Ошибка: - java.lang.IllegalStateException: Не удалось прочитать строку 0, седловины -1 от CursorWindow. Перед доступом к данным убедитесь, что курсор инициализирован правильно. на android.database.CursorWindow.nativeGetString (Native Method)

+0

Пожалуйста, добавьте дополнительную информацию о версии Android, которую вы хотите, чтобы приложение работало, это может помочь прояснить классы, которые вы можете использовать. – Zephyr

+0

этот код работает над android 4.2, поэтому я хочу запустить свой код на Android версии 4.2 или выше. – neooo

ответ

0

Вы можете прочитать все номера телефонов, связанных с контактом в следующим образом:

Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId); 
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY); 
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL} 
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null); 
+0

Что здесь такое? – neooo

0

Понял, нам нужно добавить выбор в курсор.

String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"; 
cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selection, null, null); 
Смежные вопросы