Retrieving all contact id with length 4 android - android

I need to retrieve contacts Id with that have <=7 characters and add two 0's in front and update the contact list. How can i achieve this
public class MainActivity extends Activity {
public static final int PICK_CONTACT = 1;
Uri uri;
TextView txt_contacts;
Cursor c = null;
MainActivity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
getContactList();
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.btn_contacts)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
txt_contacts =(TextView)findViewById(R.id.txt_contacts);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
uri = data.getData();
if (uri != null) {
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
String new_num = 0+number;
/*
* QUERY TO UPDATE PHONE NUMBER
*/
ContentValues _changed_values=new ContentValues();
_changed_values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,new_num);
getContentResolver().update(uri,_changed_values,
ContactsContract.CommonDataKinds.Phone._ID+"=?", new String[]{String.valueOf(type)});
txt_contacts.setText(new_num);
}
public List<Person> getContactList(){
ArrayList<Person> contactList = new ArrayList<Person>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")>'7'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
Person aContact = new Person();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
PROJECTION = new String[] {Phone.NUMBER};
final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}

You may want to take a look at this:
How to get contacts from native phonebook in android
For your case you should just have to change the SELECTION query statement to something like:
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")<='4'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);

Related

How to retrieve company name from the selected contact

Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.
But instead of returning the company name it's returning the mobile number again.
The intent I use to select a specific phone number when there are multiple numbers
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
here is the main code
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1):
if (resultCode == Activity.RESULT_OK) {
Uri contctDataVar = data.getData();
Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
if (contctCursorVar.getCount() > 0) {
while (contctCursorVar.moveToNext()) {
String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
Log.i("Names", ContctNamVar);
if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
mobile.setText(ContctMobVar);
custname.setText(ContctNamVar);
companyname.setText(Companyname2);
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
I need to find a way to retrieve the company name saved under the selected contact.
You may try something like this :
ContentResolver mContentResolver = this.getContentResolver();
Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);
private String getRawContactID(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
With the help of the solution provided by #Shiva Snape I was able to solve the problem.
Code for button to call contacts app and select the relevant number
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Code to collect Contact Number, Name and company name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
null, null, null);
ContentResolver mContentResolver = this.getContentResolver();
if (c != null && c.moveToFirst()) {
String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String Vname = null;
if (cursor.moveToFirst()) {
Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return Vname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.

Android phone contacts lookup function call from adapter.setViewBinder

I am trying to list SMS messages with corresponding contact names in list view through following code:
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "person", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, "thread_id");
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == aCursor.getColumnIndex("date")) {
String createDate = aCursor.getString(aColumnIndex);
TextView textView = (TextView) aView;
textView.setText(millisToDate(createDate));
return true;
}
else if (aColumnIndex == aCursor.getColumnIndex("address")) {
String PhoneNumber = aCursor.getString(aCursor.getColumnIndex("address"));
TextView textView = (TextView) aView;
// textView.setText(getContactName(MessageBox.this,PhoneNumber)); // this crashes
textView.setText(PhoneNumber); // this works
return true;
}
return false;
}
});
lvMsg.setAdapter(adapter);
}
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
App compiles, but crashes. However, if I use the same function code under different circumstances, it works as expected:
public void fillSMS() {
Uri uriSMSURI = Uri.parse("content://sms");
Cursor cur = getContentResolver().query(uriSMSURI, new String[]{"DISTINCT address","body","date","thread_id"}, null, null,"thread_id");
String sms = "";
while (cur.moveToNext()) {
Long d = Long.parseLong(cur.getString(cur.getColumnIndex("date"))); //for retrieve readable date, time
String PhoneNumber = cur.getString(cur.getColumnIndex("address"));
sms += "At :"+ millisToDate(d) +" From :" + getContactName(MainActivity.this,PhoneNumber)+" "+ cur.getString(cur.getColumnIndex("address"))+" : " + "\n"
+ cur.getString(cur.getColumnIndex("body"))+"\n"+"\n";
}
final TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(sms);
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
}
public static String millisToDate(long currentTime) {
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}
What am I doing wrong? Please help.
Well, this was a beginner stupidity one.
Forgot to add permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
Hope this will be informative to someone.

Android programatically getting device default phone number from contacts

I got name and contact id from android "my" contact by using this method
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
}
}
How to get phone number of the device too?
Add following permission in manifest.
<uses-permission android:name="android.permission.READ_CONTACTS" />
Use Following code to get "Me" contact.
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath( ContactsContract.Profile.CONTENT_URI,ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
//Don't select anything here null will return all available fields
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
ArrayList<String> DataArray = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//here where you get your data and its type
TypeName=cursor.getString(ProfileQuery.ADDRESS);//this will give you field name
Data=cursor.getString(ProfileQuery.NUMBER);//this will give you field data
cursor.moveToNext();
}
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.ADDRESS ,
ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Organization.DATA3,
};
int ADDRESS = 0;
int NUMBER = 1;
}
Try this:
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
And in manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
This is the proper way of doing it
1) call the intent
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
if(intent.resolveActivity(getActivity().getPackageManager()) != null) {
getParentFragment().startActivityForResult(intent, CONTACT_REQUEST_CODE);
}
2) Implement onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CONTACT_REQUEST_CODE) {
uriContact = data.getData();
// replaceAll("\\D", "") : Remove everything that is not a digit
String number = retrieveContactNumber();
if (Connectivity.isConnected(getActivity())) {
if (number != null) {
String contact_number = number.replaceAll("\\D", "");
}
}
}
}
}
3) implement retrieveContactNumber()
private String retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
// Using the contact ID to get contact phone number
Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
return contactNumber;
}
4) Enjoy :)
Try this...
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
if(Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",new String[] { contact_id }, null);
while (pCur.moveToNext()) {
String noo = pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
}
}
}
I think you should use ContactsContract.CommonDataKinds.Phone.CONTENT_URI and there is column called ContactsContract.CommonDataKinds.Phone.NUMBER using which you may get contact number.
Have a look this code
public ArrayList<String> getContactList(){
ArrayList<String> list= new ArrayList<String>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] columns = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getContentResolver().query(uri, columns, null, null, null);
int _nameIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _numberIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String name = people.getString(_nameIndex);
String number = people.getString(_numberIndex);
list.add(name+" :"+number);
// Do work...
} while (people.moveToNext());
return list;
}
This worked for me.
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
name = c.getString(1);
number= c.getString(2);
}
}

Get contact's mobile, work and home number in a string

I want to get the contact's(Saved in phonebook) mobile number, work number and home number. I want to set these numbers in my 3 edittext views. How to do this? Here is my code
Cursor phones = getActivity().getContentResolver().query(
Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + " = " + phoneId,
null,
null
);
while (phones.moveToNext()) {
number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_HOME) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
if (type == Phone.TYPE_MOBILE) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
if (type == Phone.TYPE_WORK) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
}
try this link to get the contact details like phonenumber,name from phonebook.
And check the answer posted by jon
public List<Person> getContactList(){
ArrayList<Person> contactList = new ArrayList<Person>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
Person aContact = new Person();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
PROJECTION = new String[] {Phone.NUMBER};
final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
AND PERSON CLASS
public class Person {
String myName = "";
String myNumber = "";
public String getName() {
return myName;
}
public void setName(String name) {
myName = name;
}
public String getPhoneNum() {
return myNumber;
}
public void setPhoneNum(String number) {
myNumber = number;
}
}
hope this helps you.

Get android phone books

I need some help, because I can't find any solutions on Google :-(
Is there a easy way to get the names of the phone books on my device. I want fill a spinner with these values. So I need a result which contains entries like: SIM, Google, Local, etc.
These values are accessible by the Contacts Provider (I think in ContactsContract.RawContacts) and named as ACCOUNT_TYPE and ACCOUNT_NAME. But I think it couldn't be the solution to get the values with a cursor from the Contacts Provider.
Thank you so much for any suggestions.
public List<Person> getContactList(){
ArrayList<Person> contactList = new ArrayList<Person>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
Person aContact = new Person();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
PROJECTION = new String[] {Phone.NUMBER};
final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
Person class:
public class Person {
String myName = "";
String myNumber = "";
public String getName() {
return myName;
}
public void setName(String name) {
myName = name;
}
public String getPhoneNum() {
return myNumber;
}
public void setPhoneNum(String number) {
myNumber = number;
}
}

Categories

Resources