Retrieve birthday of specific contacts - android

Contact list are retrieved from Contacts and displayed in listView. When a single contact is clicked from listview it starts a new activity i.e DetailActivity.java(code provided below). I need to show the clicked contact's birthday in DetailActivity's TextView field. How to do it?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView1 ;
ArrayList<String> nameArray, phoneArray;
ArrayAdapter<String> arrayAdapter;
Cursor cursor, birthdayCur ;
String name, birthday ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView1 = (ListView)findViewById(listView);
nameArray = new ArrayList<String>();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items,
textView, nameArray
);
listView1.setAdapter(arrayAdapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
String data = (String) adapter.getItemAtPosition(position);
Intent appInfo = new Intent(MainActivity.this, DetailActivity.class);
appInfo.putExtra("data", data);
startActivity(appInfo);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
nameArray.add(name);
}
cursor.close();
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
birthdayCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
phoneArray.add(birthday);
}
}
birthdayCur.close();
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
TextView tv1, tv2;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent i = getIntent();
data = i.getStringExtra("data");
tv1 = (TextView) findViewById(R.id.name);
tv1.setText(data);
}

you can get the birthday date of contacts, try this:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
ContentResolver bd = getContentResolver();
Cursor bdc = bd.query(android.provider.ContactsContract.Data.CONTENT_URI, new String[] { Event.DATA }, android.provider.ContactsContract.Data.CONTACT_ID+" = "+id+" AND "+Data.MIMETYPE+" = '"+Event.CONTENT_ITEM_TYPE+"' AND "+Event.TYPE+" = "+Event.TYPE_BIRTHDAY, null, android.provider.ContactsContract.Data.DISPLAY_NAME);
if (bdc.getCount() > 0) {
while (bdc.moveToNext()) {
String birthday = bdc.getString(0);
// now "id" is the user's unique ID, "name" is his full name and "birthday" is the date and time of his birth
}
}
}
}
cur.close();

Related

Getting null while fetching email address of a Contact

I am working on an application that includes dealing with Contacts also. I have tried distinct methods But none of them worked.. I am fetching contact details in one of the tabbed Activity fragments. Its fetching all other details correctly except Email Address of the contact. I have figured out the reason because ContactsContract.CommonDataKinds.Phone._ID fetching different Ids than ContactsContract.CommonDataKinds.Email.CONTACT_ID.. Now what should i code to fetch all the contacts from phone along with name, number, email, photo_uri. Please Help! Here is my piece of code:
public class FragmentContacts extends Fragment{
ListView contacts;
ArrayList<String> namelist=new ArrayList<String>();
ArrayList<String> number=new ArrayList<String>();
ArrayList<String> contact_id=new ArrayList<String>();
ArrayList<String> contact_image_uri=new ArrayList<String>();
ArrayList<String> contact_email=new ArrayList<String>();
String[] sortImage;
ImageButton addContact;
String email;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
contacts=(ListView)rootView.findViewById(R.id.contact_list);
addContact=(ImageButton)rootView.findViewById(R.id.add_contact);
namelist.clear();
getContacts();
addContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewContact();
}
});
return rootView;
}
public void getContacts() {
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor managedCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.PHOTO_URI}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
while (managedCursor.moveToNext()) {
String id = managedCursor.getString(0);
String name = managedCursor.getString(1);
String phoneNumber = managedCursor.getString(2);
String image_uri=managedCursor.getString(3);
//email=managedCursor.getString(4);
email=getEmail(id);
System.out.println("Email is "+email);
contact_id.add(id);
// System.out.println("Id is "+id+" "+"Name is "+name);
namelist.add(name);
number.add(phoneNumber);
contact_image_uri.add(image_uri);
contact_email.add(email);
}
managedCursor.close();
ContactAdapter a = new ContactAdapter(getActivity(), contact_id, namelist, number,contact_image_uri,contact_email);
contacts.setAdapter(a);
}
public void addNewContact()
{
Intent in= new Intent(getContext(),AddContact.class);
startActivity(in);
}
private String getEmail(String contactId) {
String mailE=null;
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = ?",
new String[]{contactId}, null);
while (cursor.moveToNext())
{
mailE=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
System.out.println("In Between Email is "+mailE);
}
cursor.close();
return mailE;
}
}
For Getting Email Address Email,
String email = managedCursor .getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Try this.
You can you this method to get the email ID of that contact. In your case you can pass the contact ID directly.
public ArrayList<String> getEmail() {
ArrayList<String> names = new ArrayList<String>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
if(email!=null){
names.add(name);
}
}
cur1.close();
}
}
return names;
}
There's some confusion in your code, you can't query over Phone.CONTENT_URI and expect to get an email-address, as emails are stored in Email.CONTENT_URI.
The naive way would be to add another query over Email.CONTENT_URI, but that's not needed, your best choice would be to query over the entire Data.CONTENT_URI table which contains both emails and phones (and a lot of other types of information), and ask for only mimetypes for emails and phones.
String[] projection = new String[] { Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Email.ADDRESS, Phone.NUMBER };
Cursor cur = getContentResolver().query(Data.CONTENT_URI, projection, Data.MIMETYPE + " IN ('" + Email.CONTENT_ITEM_TYPE + "' , '" + Phone.CONTENT_ITEM_TYPE +"')", null, null);
while ((cur != null) && cur.moveToNext()) {
long contactId = cur.getLong(0);
String name = cur.getString(1);
String type = cur.getString(2);
String email = null;
String phone = null;
if (type == Email.CONTENT_ITEM_TYPE) {
email = cur.getString(3);
} else {
phone = cur.getString(4);
}
// do whatever you want with above variables.
}
Note: you'll get the same contactId and name for each phone/email stored for that contact, so you should use a HashMap to map contactId to list of details, in order to store all this data.
You should definitely read first to docs about the ContactsContract API, and Contacts and Data tables, as these are crucial to understanding how to query for information about contacts.
Finally i'v resolved it. I have changed contact_id from ContactsContract.CommonDataKinds.Phone._ID to ContactsContract.CommonDataKinds.Phone.CONTACT_ID... My Updated code is:
public class FragmentContacts extends Fragment{
ListView contacts;
ArrayList<String> namelist=new ArrayList<String>();
ArrayList<String> number=new ArrayList<String>();
ArrayList<String> contact_id=new ArrayList<String>();
ArrayList<String> contact_image_uri=new ArrayList<String>();
ArrayList<String> contact_email=new ArrayList<String>();
ImageButton addContact;
String email;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
contacts=(ListView)rootView.findViewById(R.id.contact_list);
addContact=(ImageButton)rootView.findViewById(R.id.add_contact);
namelist.clear();
getContacts();
addContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewContact();
}
});
return rootView;
}
public void getContacts() {
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor managedCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.PHOTO_URI}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
while (managedCursor.moveToNext()) {
String id = managedCursor.getString(0);
String name = managedCursor.getString(1);
String phoneNumber=managedCursor.getString(2);
String image_uri=managedCursor.getString(3);
email=getEmail(id);
contact_id.add(id);
namelist.add(name);
number.add(phoneNumber);
contact_image_uri.add(image_uri);
contact_email.add(email);
}
managedCursor.close();
ContactAdapter a = new ContactAdapter(getActivity(), contact_id, namelist, number,contact_image_uri,contact_email);
contacts.setAdapter(a);
}
public void addNewContact()
{
Intent in= new Intent(getContext(),AddContact.class);
startActivity(in);
}
private String getEmail(String contactId) {
String mailE=null;
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = ?",
new String[]{contactId}, null);
while (cursor.moveToNext())
{
mailE=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
}
cursor.close();
return mailE;
}
}

How to fetch data for a specific category in listview?

My MainActivity have a listview with some categories,If I click a particular category in my listview,it's need to redirect to another activity,which need to have the details of that particular category.
Eg: IF I select FOOD in Mainactivity,I want to redirect to another activity where the activity want to have the budget amount of food.
public class addbudget extends ActionBarActivity implements View.OnClickListener{
SimpleCursorAdapter adapter;
DBhelper helper;
SQLiteDatabase db;
EditText txtBudget;
TextView txr;
ListView rldlist,list;
Button btn66;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addbudget);
btn66=(Button)findViewById(R.id.btn_addBudget);
btn66.setOnClickListener(this);
helper=new DBhelper(addbudget.this);
txr=(TextView)findViewById(R.id.addbud);
txtBudget=(EditText)findViewById(R.id.etBudget);
rldlist = (ListView) findViewById(R.id.rldlist);
list = (ListView) findViewById(R.id.list);
Bundle data_from_list= getIntent().getExtras();
String value_in_tv= data_from_list.getString("passed data key");
txr.setText(value_in_tv);
fetchData2();
}
private void clearfield(){
txtBudget.setText("");
}
public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description,txr.getText().toString());
if (txtBudget.length() == 0) {
txtBudget.requestFocus();
txtBudget.setError("Field Cannot Be Empty");
} else {
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
}
}
}
private void fetchData2() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE2, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
}
This is how ,I'm fetching data to a listview from database.Here I'm fetching Amount from database.
How can I change the fetchdata method to get the BudgetAmount of a specific category ?(I'm using bundle to get the name of the category from the listview of MainActivity)
You can use sql syntax:
String sql = "select * from DBhelper.TABLE2 where category_name_column = " + category";
Cursor c = db.rawQuery(sql.toString(), null);
Or if you want to use params:
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {
"category_name"
};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
So your method can be as such:
private void fetchData2(String category) {
db = helper.getReadableDatabase();
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {"category"};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}

android have 8000 contacts render in Application

Application need to read the phonebook contacts and show it to the user, have more than 8000 contacts on the phone.
Problem is it stuck for very long time while rendering all contacts on the screen.
Please suggest best way to accomplish this task. thanks
Main Method:
Cursor contactsCursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
LogUtils.d("### cursorCount" + contactsCursor.getCount());
contacts = new ArrayList<ImportContactModel>();
importContactList = new ArrayList<ImportContactModel>();
showProgressDialog();
asyncLoader = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
fetchContacts();
return null;
}
protected void onPostExecute(Void result) {
// create an array of Strings, that will be put to our
// ListActivity
adapter = new ImportContactArrayAdapter(
ImportContactSelection.this, contacts);
contactList.setAdapter(adapter);
contactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
initSearch();
dismissProgressDialog();
};
}.execute();
Class to get Data:
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String PROFILE_PIC = ContactsContract.CommonDataKinds.Phone.PHOTO_URI;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EMAIL_CONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EMAIL_CONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
ImportContactModel tempContact = new ImportContactModel();
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
String image_uri = cursor.getString(cursor
.getColumnIndex(PROFILE_PIC));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
tempContact.setId(contact_id);
if (image_uri != null)
tempContact.setProfilePic(cursor.getString(cursor
.getColumnIndex(PROFILE_PIC)));
else
tempContact.setProfilePic("");
tempContact.setContactName(name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
// Get All Phone Numbers
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
tempContact.setContactNo(phoneNumber);
break;
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
EMAIL_CONTENT_URI, null, EMAIL_CONTACT_ID + "=?",
new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
String contactId = emailCursor.getString(emailCursor
.getColumnIndex(EMAIL_CONTACT_ID));
email = emailCursor.getString(emailCursor
.getColumnIndex(EMAIL));
tempContact.setEmail(email);
break;
}
emailCursor.close();
contacts.add(tempContact);
}
}
}
}
Adapter Class
public class ImportContactArrayAdapter extends ArrayAdapter<ImportContactModel> {
private final List<ImportContactModel> list;
private final Activity context;
private ImageLoader mImageLoader;
public ImportContactArrayAdapter(Activity context, List<ImportContactModel> list) {
super(context, R.layout.item_task_contact_select, list);
this.context = context;
this.list = list;
this.mImageLoader = ImageLoader.getInstance();
}
static class ViewHolder {
protected ImageView profilePic;
protected TextView contactName;
protected TextView contactNo;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.item_task_contact_select, null);
final ViewHolder viewHolder = new ViewHolder();
//viewHolder.profilePic = (ImageView) view.findViewById(R.id.img_import_profilePic);
viewHolder.contactName = (TextView) view.findViewById(R.id.name_text);
viewHolder.contactNo = (TextView)view.findViewById(R.id.tag_text_1);
viewHolder.contactNo.setVisibility(View.VISIBLE);
viewHolder.contactNo.setTextSize(11);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.select_checkbox);
viewHolder.checkbox.setClickable(true);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
ImportContactModel element = (ImportContactModel) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
ImageView avatar = (ImageView) view.findViewById(R.id.img_avatar);
ImageView avatarBorder = (ImageView) view.findViewById(R.id.img_avatar_overlay);
ProgressBar avatarProgress = (ProgressBar) view.findViewById(R.id.img_avatar_progress);
if(!list.get(position).equals(""))
//holder.profilePic.setImageURI(Uri.parse(list.get(position).getProfilePic()));
mImageLoader.displayImage(list.get(position).getProfilePic(), avatar, new AvatarsImageLoadingListener(avatarProgress, avatarBorder, R.drawable.bg_nophoto));
holder.contactName.setText(list.get(position).getContactName());
holder.contactNo.setText(list.get(position).getContactNo());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
public ArrayList<ImportContactModel> getCheckList(){
ArrayList<ImportContactModel> tempList = new ArrayList<ImportContactModel>();
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
tempList.add(list.get(i));
LogUtils.d(""+list.get(i).getContactName());
}
}
return tempList;
}
}
So it just shows Loading screen for huge amount of time..
You don't have to fetch all contacts to display them. AsyncTask has publishProgress method. I'm not experienced with Cursor class, since I prefer ORM for that, so I'll write in pseudo code, you'll have to adapt it yourself.
//in AsyncTask
protected Void doInBackground(params){
while(cursor.moveToNext()){
contactInfo = createContact(currentCursorValue);
publishProgress(contactInfo);
}
}
onProgressUpdate(contactInfo){
if(adapter==null){
//first time adapter setup
}
adapter.add(contactInfo);
adapter.notifyDataSetChanged();
}
This way, every time you pull a record from Db, you publish it, and items are added continuously. User won't notice any delay, unless he tries searching for not yet existing items, or you want to implement that big pop up letter for fast scroll. Still, above code is not very effective, since publishing the progress every .001 second or so, is not very smart, so you can either publish every 20 results, or publish them every second, up to you.

how to remove duplicate contacts from arraylist

I have created an app in which I am getting the contacts from a device.
But I want to remove the duplicate contacts from the results.
How could I do it?
MainActivity
public class MainActivity extends Activity implements OnItemClickListener {
EditText searchText;
ArrayList<String> phno0 = new ArrayList<String>();
List<String> arrayListNames;
public List<ProfileBean> list;
public SearchableAdapter adapter;
//ProfileBean bean;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
lv = (ListView) findViewById(R.id.listview);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplication(), list);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(this);
lv.setTextFilterEnabled(true);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
phones.close();
}
}
If you want to get rid of duplicates, consider using a HashSet instead.
If you can't/don't want to use it, simply check before adding whether the contact is already there.
if (!myList.contains(newContact))
myList.add(newContact);
Add the following checking in the place of list.add(new ProfileBean(name, phoneNumber)); before adding into list:
int flag = 0
if(list.size() == 0){
list.add(new ProfileBean(name, phoneNumber));
}
for(int i=0;i<list.size();i++){
if(!list.get(i).getProfileName().trim().equals(name)){
flag = 1;
}else{
flag =0;
break;
}
}
if(flag == 1){
list.add(new ProfileBean(name, phoneNumber));
}
The following function can be used for removing duplicates from String ArrayList Change it according to your requirement
public ArrayList<String> listWithoutDuplicates(ArrayList<String> duplicateList) {
// Converting ArrayList to HashSet to remove duplicates
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(duplicateList);
// Creating Arraylist without duplicate values
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
return listWithoutDuplicates;
}
use below code list=removeDuplicates(list);
public List<ProfileBean> removeDuplicates(List<ProfileBean> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
if (((ProfileBean) o1).getName().equalsIgnoreCase(((ProfileBean) o2).getName()) &&
((ProfileBean)o1).getPhoneNumber().equalsIgnoreCase(((ProfileBean)o2).getPhoneNumber())) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}
Try to get ContactsContract.Contacts.NAME_RAW_CONTACT_ID) its unique id and its used for update contacts compare your contacts with raw id is same or not as below
private void getAllContactsBackground() {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactsModel info = new ContactsModel();
info.contacts_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
info.contacts_raw_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
info.contacts_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.contacts_mobile = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceFirst("[^0-9]" + "91", "");
info.contacts_photo = photo;
info.contacts_photoURI = String.valueOf(pURI);
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
info.contacts_email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("email==>", "" + info.contacts_email);
}
emailCur.close();
int flag = 0;
if (arrayListAllContacts.size() == 0) {
arrayListAllContacts.add(info);
}
for (int i = 0; i < arrayListAllContacts.size(); i++) {
if (!arrayListAllContacts.get(i).getContacts_raw_id().trim().equals(info.contacts_raw_id)) {
flag = 1;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
arrayListAllContacts.add(info);
}
}
cursorInfo.close();
}
}
cursor.close();
}
}

I want to select a number from the contact book in Android

This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}

Categories

Resources