Unfortunately I have unable to found any help regarding this.
Actually I want to fetch all available calendars(may be calendar preference) list from mobile for example Google calendar, yahoo calendar.
For better explanation I captured some images from Smooth Calendar application which is in below image after config button click from the widget.
==>
Here the Calendars preference showing all calendars available in phone and after choosing the Calendars option it shows all calendars to select what user wants.
Can someone helps me here and shares some knowledge that how to do this.
Thanks
To get all available calendars from mobile hope so this code will help.
Cursor cursor;
if (android.os.Build.VERSION.SDK_INT <= 7) {
cursor = getContentResolver().query(Uri.parse("content://calendar/calendars"), new String[] { "_id", "displayName" }, null,
null, null);
}
else if (android.os.Build.VERSION.SDK_INT <= 14) {
cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayName" }, null, null, null);
}
else {
cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "calendar_displayName" }, null, null, null);
}
// Get calendars name
Log.i("#calendar","Cursor count " + cursor.getCount());
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String[] calendarNames = new String[cursor.getCount()];
// Get calendars id
int calendarIds[] = new int[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
calendarIds[i] = cursor.getInt(0);
calendarNames[i] = cursor.getString(1);
Log.i("#calendar","Calendar Name : " + calendarNames[i]);
cursor.moveToNext();
}
} else {
Log.e("#calendar","No calendar found in the device");
}
Fortunately I have found some help from developer site and able to get all available calendars and show them with dynamic Checkpreferences.
hope my code will help some one in future.
CalendarPreference.java
public class CalendarPreference extends PreferenceActivity{
private static final String CALENDAR_ID = "calendarId";
private static final String[] PROJECTION = new String[] { Calendars._ID,
Calendars.CALENDAR_DISPLAY_NAME, Calendars.CALENDAR_COLOR };
private Set<String> initialActiveCalendars;
CheckBoxPreference mCheckBoxPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.calendaraccounts);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
initialActiveCalendars = prefs.getStringSet("PREF_ACTIVE_CALENDARS", null);
populatePreferenceScreen(initialActiveCalendars);
}
private void populatePreferenceScreen(Set<String> activeCalendars) {
Cursor cursor = createLoadedCursor();
if (cursor == null) {
return;
}
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setTitle(cursor.getString(1));
checkboxPref.setIcon(createDrawable(cursor.getInt(2)));
int calendarId = cursor.getInt(0);
checkboxPref.getExtras().putInt(CALENDAR_ID, calendarId);
checkboxPref.setChecked(activeCalendars == null
|| activeCalendars.contains(String.valueOf(calendarId)));
getPreferenceScreen().addPreference(checkboxPref);
}
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
return true;
}
private Cursor createLoadedCursor() {
Uri.Builder builder = Calendars.CONTENT_URI.buildUpon();
ContentResolver contentResolver = getContentResolver();
return contentResolver.query(builder.build(), PROJECTION, null, null, null);
}
#Override
public void onPause() {
super.onPause();
HashSet<String> selectedCalendars = getSelectedCalenders();
if (!selectedCalendars.equals(initialActiveCalendars)) {
persistSelectedCalendars(selectedCalendars);
Log.v("Selected Calendars", selectedCalendars.toString());
NewWidget.updateAllWidgets(this);
}
}
private void persistSelectedCalendars(HashSet<String> prefValues) {
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
Editor editor = prefs.edit();
editor.putStringSet("PREF_ACTIVE_CALENDARS", prefValues);
editor.commit();
}
private HashSet<String> getSelectedCalenders() {
PreferenceScreen preferenceScreen = getPreferenceScreen();
int prefCount = preferenceScreen.getPreferenceCount();
HashSet<String> prefValues = new HashSet<String>();
for (int i = 0; i < prefCount; i++) {
Preference pref = preferenceScreen.getPreference(i);
if (pref instanceof CheckBoxPreference) {
CheckBoxPreference checkPref = (CheckBoxPreference) pref;
if (checkPref.isChecked()) {
prefValues.add(String.valueOf(checkPref.getExtras().getInt(CALENDAR_ID)));
}
}
}
return prefValues;
}
private Drawable createDrawable(int color) {
Drawable drawable = getResources().getDrawable(R.drawable.prefs_calendar_entry);
drawable.setColorFilter(new LightingColorFilter(0x0, color));
return drawable;
}
}
And here res/xml/calendaraccounts.xml
<PreferenceScreen>
</PreferenceScreen>
Related
I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}
I'm developping an Android App.
In my first Activity I list conversations and on conversation click, app launch an other activity with list of sms for the conversation.
But, on back press, I get that exception :
java.lang.RuntimeException: Unable to resume activity {com.example/com.example.activity.TalksActivity_}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
List conversations :
public static List<Talk> getTalks(Activity context) {
List<Talk> listTalk = new ArrayList<>();
Talk objTalk;
Cursor cur= context.getContentResolver().query(Uri.parse("content://mms-sms/conversations?simple=true"), null, null, null, null);
context.startManagingCursor(cur);
Log.w(TAG, "getTalks");
int total = cur.getCount();
if(cur.moveToFirst())
{
for (int i = 0; i < total; i++) {
objTalk = new Talk();
String snippet = cur.getString(cur.getColumnIndexOrThrow("snippet"));
if (snippet.length() > 30) {
objTalk.setSnippet(snippet.substring(0, 27)+"...");
} else {
objTalk.setSnippet(snippet);
}
Date date = DateHelper.getDate(Long.parseLong(cur.getString(1)));
objTalk.setDate(date);
objTalk.setDateString(DateHelper.formatDate(date));
String id = cur.getString(cur.getColumnIndexOrThrow("_id")).toString();
objTalk.setId(id);
String recipientId = cur.getString(cur.getColumnIndexOrThrow("recipient_ids")).toString();
Cursor c2= context.getContentResolver().query(Uri.parse("content://mms-sms/canonical-addresses"), null, "_id = " + recipientId, null, null);
context.startManagingCursor(c2);
if(c2.moveToFirst())
{
String phoneNumber = c2.getString(1);
objTalk.setContact(getContact(context, phoneNumber));
listTalk.add(objTalk);
}
c2.close();
cur.moveToNext();
}
}
cur.close();
return listTalk;
}
List SMS :
public static Contact getContact(Activity context, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String name;
long id;
Contact contact = new Contact();
ContentResolver contentResolver = context.getContentResolver();
Cursor contactLookup = contentResolver.query(uri, new String[] {ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_FILE_ID }, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
id = contactLookup.getLong(contactLookup.getColumnIndex(ContactsContract.PhoneLookup._ID));
contact.setId(id);
contact.setName(name);
}
else
{
contact.setId(-1);
contact.setName(phoneNumber);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return contact;
}
public static List<Sms> getAllSms(Activity context, String talkId) {
List<Sms> receivedSmsList = getSmsList(context, "content://sms/inbox", talkId, false);
List<Sms> sentSmsList = getSmsList(context,"content://sms/sent", talkId, true);
List<Sms> allSms = new ArrayList<>();
allSms.addAll(receivedSmsList);
allSms.addAll(sentSmsList);
Collections.sort(allSms);
return allSms;
}
private static List<Sms> getSmsList(Activity context, String uri, String talkId, boolean isSent) {
List<Sms> smsList = new ArrayList<>();
Sms objSms;
Log.w(TAG, "getSmsList talkId="+talkId);
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(Uri.parse(uri), null, "thread_id="+talkId, null, null);
context.startManagingCursor(c);
if (c == null || c.getCount() == 0) {
c.close();
Log.w(TAG, "getSmsList cursor is null");
return new ArrayList<>();
}
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
Log.w(TAG, i+" -> getSmsList sms id="+c.getString(c.getColumnIndexOrThrow("_id"))+" msg="+c.getString(c.getColumnIndexOrThrow("body")));
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setSent(isSent);
Date date = DateHelper.getDate(Long.parseLong(c.getString(c.getColumnIndexOrThrow("date"))));
objSms.setDate(date);
objSms.setDateString(DateHelper.formatDate(date));
smsList.add(objSms);
c.moveToNext();
}
}
c.close();
return smsList;
}
EDIT
Conversations Activity code (Sms activity is same) :
public class ConversationsActivity extends AppCompatActivity {
#AfterViews
void afterViews() {
// [...init adapter...]
mAdapter.addAll(SmsHelper.getTalks(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecyclerView.setAdapter(mAdapter);
}
EDIT 2
If I don't call .close() on my cursors, it don't crash !
But... Isn't it too durty ?
I have created one App. In this app I want to get Data from Database using Getter and Setter method. I don't Know how can I do that. Please help me. Necessary Code is here:
DisplayMedia.java
public class DisplayMedia extends Activity {
ImageView displayImage;
VideoView displayVideo;
TextView txtMediaDate,txtMediaTime,txtMediaAddress;
DatabaseHelper dbHelper;
Intent intent;
String mediaPath,mediaDate,mediaTime,mediaAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_media);
displayImage = (ImageView) findViewById(R.id.displayImage);
displayVideo = (VideoView) findViewById(R.id.displayVideo);
txtMediaDate = (TextView) findViewById(R.id.txtMediaDate);
txtMediaTime = (TextView) findViewById(R.id.txtMediaTime);
txtMediaAddress = (TextView) findViewById(R.id.txtMediaAddress);
dbHelper = new DatabaseHelper(getApplicationContext());
mediaPath = dbHelper.displayImages();
File mediaFile = new File(mediaPath);
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
displayVideo.setVisibility(View.GONE);
displayImage.setVisibility(View.VISIBLE);
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
displayImage.setImageBitmap(scale);
} else {
displayImage.setVisibility(View.GONE);
displayVideo.setVisibility(View.VISIBLE);
displayVideo.setVideoURI(Uri.parse(mediaFile.toString()));
displayVideo.start();
}
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}
}
DataBaseHelper.java
public void insertMedia(String mPath,String mDate,String mTime,String mAddress) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
cur = db.query(INCIDENT, null, null, null, null, null, null);
cur.moveToFirst();
values.put("mediaPath", mPath);
values.put("mediaDate", mDate);
values.put("mediaTime", mTime);
values.put("mediaAddress", mAddress);
db.insert(INCIDENT, null, values);
db.close();
}
public String displayMedia() {
db = this.getReadableDatabase();
cur = db.query(INCIDENT, null, null, null, null, null, null);
String path = null,date = null, time = null, address = null;
cur.moveToFirst();
while (cur.isAfterLast() == false) {
path = (cur.getString(0));
date = (cur.getString(1));
time = (cur.getString(2));
address = (cur.getString(3));
cur.moveToNext();
}
return path;
}
In this app I inserted data in data base successfully. In my data base following data has stored:
MediaPath, MediaDate, MediaTime, MediaAddress
Now I want to get all data using above displayMedia(). how can I do that?
You can get a Cursor Object contains all the table data inside:
public Cursor getCursor() {
db = this.getReadableDatabase();
return db.query(INCIDENT, null, null, null, null, null, null);
}
And then, wherever You need it, You can get the information like:
Cursor c = yourDatabaseClass.getCursor();
int rows = c.getCount();
for(int i=0;i<rows;i++){
String path = c.getString(0);
String date = c.getString(1);
String time = c.getString(2);
String adress = c.getString(3);
c.moveToNext();
}
Then it´s up to You how You want to display path/date/time/adress information.
My app is taking forever to load,how can I use paging that's it would load me like 10-15 people in a page and not to take 2 minute to my app for loading??
this is my code:
thank's for the help
public class Contacts extends Util<Contact> {
public Contacts(Activity activity) {
super(activity);
}
#Override
public void init() {
list = getContactsBasic();
for (int i = 0; i < list.size(); i++) {
Contact current = list.get(i);
current.image = getContactImage(current.id);
if (current.hasPhone) {
current.phones = getContactPhones(current.id);
}
}
}
LinkedList<Contact> getContactsBasic() {
Uri contactsUri = android.provider.ContactsContract.Contacts.CONTENT_URI;
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, null);
LinkedList<Contact> list = new LinkedList<Contact>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
int hasPhone = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.HAS_PHONE_NUMBER));
// add more columns here
boolean hasPhoneBoolean; //editor: or simply: boolean hasPhoneBoolean = (hasPhone == 1)
if (hasPhone == 1){
hasPhoneBoolean = true;
}
else {
hasPhoneBoolean = false;
}
Contact contact = new Contact(id, name, hasPhoneBoolean);
//Contact contact = new Contact(id, name, (hasPhone == 1) ? true : false);
list.add(contact);
}
while (cursor.moveToNext());
}
cursor.close();
}
return list;
}
LinkedList<Phone> getContactPhones(int id) {
Uri phonesUri = android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + String.valueOf(id);
Cursor cursor = activity.getContentResolver().query(phonesUri, null, filter, null, null);
LinkedList<Phone> list = new LinkedList<Phone>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = cursor.getInt(cursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.TYPE));
Phone phone = new Phone(number, type);
list.add(phone);
}
while (cursor.moveToNext());
}
Change
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, null);
to
Cursor cursor = activity.getContentResolver().query(contactsUri, null, null, null, "ASC LIMIT " + HOW_MANY_ROWS_YOU_NEED);
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();
}
}