package com.example.androidquerycontacts;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.support.v4.content.CursorLoader;
import android.app.Activity;
import android.database.Cursor;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textContacts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textContacts = (TextView)findViewById(R.id.contacts);
Uri queryUri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
CursorLoader cursorLoader = new CursorLoader(
this,
queryUri,
projection,
selection,
null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int columnIndex_ID = cursor.getColumnIndex(Contacts._ID);
int columnIndex_DISPLAYNAME = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
String myContacts = "Contacts:\n";
while(cursor.moveToNext()){
int id = cursor.getInt(columnIndex_ID);
String displayName = cursor.getString(columnIndex_DISPLAYNAME);
myContacts += String.valueOf(id) + " : " + displayName +"\n";
}
textContacts.setText(myContacts);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/contacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
Permission of "android.permission.READ_CONTACTS" is needed in AndroidManifest.xml.
Download the files.
Next:
- Query Contacts database for contacts with phone number only
- Query Contacts database, search with selection of LIKE cause
- Query Contacts database, selection with AND to combine more cause
- Query Contacts database, display in ListView
- Handle Item Click on Query Contacts database ListView
- Access ContactsContract.CommonDataKinds.Phone via LOOKUP_KEY
- Get Email from Contacts database
0 comments:
Post a Comment