Modifying starred contacts - android

I need (for practicing reasons) to change all the contacts to be starred. So I use this code to read all the contacts in a thread:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
contactId = oCursor.getColumnIndex(ContactsContract.RawContacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int number = oCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
} while (oCursor.moveToNext());
}
This code works and iterates through all the contacts in the device, displaying if they are starred or not.
My problem comes when I want to modify the starred field in the loop:
...
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
ChangeStarred(sId, true); <-- HERE!!!!!!!!
} while (oCursor.moveToNext());
...
This is the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred){
ContentValues values = new ContentValues();
if(bStarred==true)
values.put(ContactsContract.Contacts.STARRED, 1);
else
values.put(ContactsContract.Contacts.STARRED, 0);
//int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.Contacts._ID + "= ?", new String[] { sContactId });
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.RawContacts._ID + "= ?", new String[] { sContactId });
if(iAffectedRows == 0)
return false;
return true;
}
This function always returns FALSE. No rows are updated.
As you can see in the code comments, I have tried with Contacts._ID and RawContacts._ID
I also have WRITE_CONTACTS permission granted.

This is how I solved:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + "\nStarred: " + sStarred;
ChangeStarred(sId, true);
} while (oCursor.moveToNext());
}
And the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred) {
ContentValues contentValues = new ContentValues();
if(bStarred==true)
contentValues.put(ContactsContract.Contacts.STARRED, 1);
else
contentValues.put(ContactsContract.Contacts.STARRED, 0);
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, contentValues, ContactsContract.Contacts._ID + "=" + sContactId, null);
if(iAffectedRows > 0)
return true;
return false;
}

Related

Android fetch all contact list (name, email, phone) takes more then a minute for about 700 contacts

Is there any way to shorten this time?
I'm running with the cursor and takes the name, phone numbers and emails
if I remove the phone numbers query from the query loop it ends in 3 seconds
any idea how can I improve that query?
Maybe I'm doing something wrong in my query?
(Obviously I'm doing it async but still... it's a very long time that a user can't wait)
Hope someone can share his thoughts about this
this is my code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
AddressBookEntity adr = new AddressBookEntity();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
adr.fullName = name;
Cursor emailCur = cr
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (!Utils.IsNullOrEmptyString(email)) {
adr.email = email;
}
}
emailCur.close();
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);
int phoneIndex = 0;
while (pCur.moveToNext()) {
String number = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
String country = Utils.GetCountryFromNumber(
number, app);
number = Utils.GetFullPhoneNumber(number, app);
if (phoneIndex == 0) {
if (!Utils.IsNullOrEmptyString(number)) {
adr.contactAdressBookId = id;
adr.phoneNumber = number;
adr.userInsertedId = app.userCred.userId;
adr.country = country;
myContacts.add(adr);
}
} else {
if (!Utils.IsNullOrEmptyString(number)) {
AddressBookEntity adrMore = new AddressBookEntity();
adrMore.fullName = adrMore.fullName;
adrMore.country = adrMore.country;
adrMore.email = adrMore.email;
adrMore.phoneNumber = number;
adrMore.contactAdressBookId = id;
adrMore.country = country;
myContacts.add(adrMore);
}
}
}
pCur.close();
}
}
cur.close();
with the following code for 59 contacts i got the following results on the emulator:
D ╔══════ query execution stats ═══════
D ║ got 59 contacts
D ║ query took 0.012 s (12 ms)
D ╚════════════════════════════════════
ok, that was the best time, but the average is 25-35 ms (for 59 contacts), add the following code in some onClick callback and run in several times in order to get the average time, in your case you should get 30 * 700 / 59 = ~300-400 ms, not 3 seconds, let alone one minute ;)
it uses Uri set to Contactables.CONTENT_URI added in API level 18 but you can use ContactsContract.Data.CONTENT_URI when building for pre 18 API devices
List<AddressBookContact> list = new LinkedList<AddressBookContact>();
LongSparseArray<AddressBookContact> array = new LongSparseArray<AddressBookContact>();
long start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
// ok, let's work...
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setTextSize(20);
tv.setBackgroundColor(0xff000033);
tv.setPadding(24, 8, 24, 24);
tv.setText(msg);
ll.addView(tv);
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
ll.addView(lv);
new AlertDialog.Builder(this).setView(ll).setPositiveButton("close", null).create().show();
the helper AddressBookContact class:
class AddressBookContact {
private long id;
private Resources res;
private String name;
private LongSparseArray<String> emails;
private LongSparseArray<String> phones;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append("\u001b[1m").append(name).append("\u001b[0m");
} else {
builder.append(name);
}
if (phones != null) {
builder.append("\n\tphones: ");
for (int i = 0; i < phones.size(); i++) {
int type = (int) phones.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, ""))
.append(": ")
.append(phones.valueAt(i));
if (i + 1 < phones.size()) {
builder.append(", ");
}
}
}
if (emails != null) {
builder.append("\n\temails: ");
for (int i = 0; i < emails.size(); i++) {
int type = (int) emails.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, ""))
.append(": ")
.append(emails.valueAt(i));
if (i + 1 < emails.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (emails == null) {
emails = new LongSparseArray<String>();
}
emails.put(type, address);
}
public void addPhone(int type, String number) {
if (phones == null) {
phones = new LongSparseArray<String>();
}
phones.put(type, number);
}
}
try this code ,use a progress dialouge
public void getAllContacts() {
new AsyncTask<String, String, ArrayList<UserInfo>>() {
ArrayList<UserInfo> infos = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<UserInfo> doInBackground(String... params) {
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER }, null, null, null);
if(cursor.getCount()>0)
while ( cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.d("TAG", " Name: " + displayName);
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
} cursor.close();
return null;
}
#Override
protected void onPostExecute(ArrayList<UserInfo> aVoid) {
super.onPostExecute(aVoid);
// EventBus.getDefault().post(aVoid);
}
}.execute();
}
You retrieve all columns in your query:
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
This makes the data processing much slower. If you define an array of columns which you really need to retrieve, it will be much faster.

How to access MISSED_CALL Log in Android

I am developing an app in which i want to access MISSED_CALL log. Using below code....
private Cursor getItemsToSync() {
G = "Log method accessing";
ContentResolver r = getContentResolver();
String selections = String.format("%s > ?", CallLog.Calls.DATE,CallLog.Calls.MISSED_TYPE);
String[] selectionArgs = new String[] { String.valueOf(getMaxSyncedDate())};
String sortOrder = SmsConsts.DATE + " LIMIT " + PrefStore.getMaxItemsPerSync(this);
N = CallLog.Calls.CACHED_NAME;
return r.query(Uri.parse("content://call_log/calls"), null,selections,selectionArgs, sortOrder);}
its provide All Call Log. Please suggest me how to get only MISSED_CALL Call log. Thanks in advance
String[] strFields = {android.provider.CallLog.Calls.CACHED_NAME, android.provider.CallLog.Calls.NUMBER,android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.TYPE
};
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor mCallCursor = getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI,strFields, null, null, strOrder);
if (mCallCursor.moveToFirst()) {
do {
boolean missed = mCallCursor.getInt(mCallCursor.getColumnIndex(CallLog.Calls.TYPE)) == CallLog.Calls.MISSED_TYPE;
if (missed) {
String name = mCallCursor.getString(mCallCursor
.getColumnIndex(CallLog.Calls.CACHED_NAME));
String number = mCallCursor.getString(mCallCursor
.getColumnIndex(CallLog.Calls.NUMBER));
Log.d("PhoneLog", "You have a missed call from " + name + " on " + number // + " at " + time); }
} while (mCallCursor.moveToNext());
}

Retrieving Data of last added event from android calendar

I want to retrive the data of last added event from android calendar. I am using this code to get last id.
public static long getNewEventId(ContentResolver cr, Uri cal_uri)
{
Uri local_uri = cal_uri;
if (cal_uri == null)
{
local_uri = Uri.parse("content://com.android.calendar/events");
}
Cursor cursor = cr.query(local_uri,
new String[] { "MAX(_id) as max_id" }, null, null, "_id");
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
return max_val + 1;
}
And then I simply add an event using this code:
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", SelectedDate);
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FsREQ=DAILY");
intent.putExtra("endTime", SelectedDate + 60 * 60 * 1000);
intent.putExtra("title", "Advance Scheduler Event");
startActivity(intent);
After this I simply retrieve the data of this event using this code:
public CalendarData EventDetails(int ID)
{
CalendarData temp = null;
// -------------------------------------------------------------------------------
ContentResolver cr = getContentResolver();
Cursor cursor_calendar;
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
{
cursor_calendar = cr.query(
Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayname" }, null, null, null);
}
else
{
cursor_calendar = cr.query(
Uri.parse("content://calendar/calendars"), new String[] {
"_id", "displayname" }, null, null, null);
}
cursor_calendar.moveToFirst();
String[] CalNamess = new String[cursor_calendar.getCount()];
int[] CalIdss = new int[cursor_calendar.getCount()];
for (int i = 0; i < CalNamess.length; i++)
{
CalIdss[i] = cursor_calendar.getInt(0);
CalNamess[i] = cursor_calendar.getString(1);
cursor_calendar.moveToNext();
}
cursor_calendar.close();
// -------------------------------------------------------------------------------
Cursor cursor_event;
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
{
cursor_event = cr.query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null, null,
null);
}
else
{
cursor_event = cr.query(Uri.parse("content://calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null, null,
null);
}
boolean flag = false;
String add = null;
cursor_event.moveToFirst();
String[] CalNames = new String[cursor_event.getCount()];
int[] CalIds = new int[cursor_event.getCount()];
for (int i = 0; i < CalNames.length; i++)
{
CalIds[i] = cursor_event.getInt(0);
if (ID == CalIds[i])
{
flag = true;
Toast.makeText(getApplicationContext(),
"ID Found : " + CalIds[i], Toast.LENGTH_LONG).show();
CalNames[i] = "Event"
+ cursor_event.getInt(0)
+ ": \nTitle: "
+ cursor_event.getString(1)
+ "\nDescription: "
+ cursor_event.getString(2)
+ "\nStart Date: "
+ cursor_event.getLong(cursor_event
.getColumnIndex("dtstart"))
+ cursor_event.getLong(cursor_event
.getColumnIndex("dtend"))
+ cursor_event.getString(5);
temp = new CalendarData();
temp.Title = cursor_event.getString(1);
temp.Description = cursor_event.getString(2);
// temp.StartDate = new Date(cursor_event.getLong(3));
// temp.EndDate = new Date(cursor_event.getLong(4));
temp.StartDate = cursor_event.getLong(cursor_event
.getColumnIndex("dtstart"));
temp.EndDate = cursor_event.getLong(cursor_event
.getColumnIndex("dtend"));
temp.Location = cursor_event.getString(5);
break;
}
cursor_event.moveToNext();
}
return temp;
}
But I can't get the data of this event. I am not getting where is the problem. Please, help me to solve this.
use this code. its working in my aap
public long GetMaxID(ContentResolver cr, Uri cal_uri, Context context)
{
Uri local_uri = cal_uri;
if (cal_uri == null)
{
// local_uri = Uri.parse("content://calendar/calendars/" +
// "events");
local_uri = Uri.parse("content://com.android.calendar/events");
}
Cursor cursor = cr.query(local_uri, new String[]
{ "MAX(_id) as max_id" }, null, null, "_id");
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
return max_val + 1;
}
public static CalendarData GetEventDetails(String ID, Context context)
{
CalendarData temp = null;
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display
// names and whether the
cursor = contentResolver.query(
Uri.parse("content://com.android.calendar/calendars"),
(new String[]
{ "_id", "displayName", "selected" }), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0)
{
System.out
.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext())
{
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: "
+ displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch (AssertionError ex)
{
ex.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to
// the end of next week.
// for (String id : calendarIds)
for (int id = 0; id <= calendarIds.size(); id++)
{
Uri.Builder builder = Uri.parse(
"content://com.android.calendar/instances/when")
.buildUpon();
// Uri.Builder builder =
// Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris
.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris
.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[]
{ "_id", "title", "begin", "end", "allDay" },
"Calendars._id=" + id, null, null);
System.out.println(id + " eventCursor count="
+ eventCursor.getCount());
if (eventCursor.getCount() > 0)
{
eventCursor.moveToFirst();
while (eventCursor.moveToNext())
{
Object mbeg_date, beg_date, beg_time, end_date, end_time;
final String eventID = eventCursor.getString(0);
final String title = eventCursor.getString(1);
final Date begin = new Date(eventCursor.getLong(2));
final Date end = new Date(eventCursor.getLong(3));
final Boolean allDay = !eventCursor.getString(4)
.equals("0");
if (eventID.equals(ID))
{
temp = new CalendarData();
temp.Title = eventCursor.getString(1);
temp.StartDate = eventCursor.getLong(2);
temp.EndDate = eventCursor.getLong(3);
break;
}
}
}
// break;
}
return temp;
}
I used the following code to retrieve all the data on the Calendar which is:
cr = getApplicationContext().getContentResolver();
caluri=CalendarContract.Events.CONTENT_URI;
atteuri=CalendarContract.Attendees.CONTENT_URI;
try
{
cur1 = cr.query(caluri, new String[]{Events.CALENDAR_ID,Events._ID, Events.TITLE, Events.DESCRIPTION,Events.DTSTART, Events.DTEND, Events.EVENT_LOCATION }, null, null, null);
if(cur1!=null){
while(cur1.moveToNext()){
cal_ID=cur1.getString(cur1.getColumnIndex(Events.CALENDAR_ID));
event_ID=cur1.getString(cur1.getColumnIndex(Events._ID));
cur2=cr.query(atteuri,new String[]{Attendees.ATTENDEE_NAME,Attendees.ATTENDEE_EMAIL}, Attendees.EVENT_ID +"=" +event_ID, null, null);
if(cur2!=null){
while(cur2.moveToNext()){
event_Title=cur1.getString(cur1.getColumnIndex(Events.TITLE));
event_Desc=cur1.getString(cur1.getColumnIndexOrThrow(Events.DESCRIPTION));
event_Start=new Date(cur1.getLong(cur1.getColumnIndex(Events.DTSTART)));
event_end=new Date(cur1.getLong(cur1.getColumnIndex(Events.DTEND)));
event_loc=cur1.getString(cur1.getColumnIndex(Events.EVENT_LOCATION));
attendee_name=cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_NAME));
attendee_Email=cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_EMAIL));
all_attendee +="\n"+attendee_name;
all_Emails +="\n"+attendee_Email;
}
cur2.close();
}
all +="Event title: " + event_Title + "\n" + "Event Description: " + event_Desc + "\n" +"Event Start: " + event_Start + "\n" + "Events End: " + event_end + "\n" + "Event Location: " + event_loc + "\n" + "Attendees: " + "\n" + all_attendee + "\n" + "Emails: "+ "\n" + all_Emails + "\n";
}
cur1.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
SO all what you need as I guess is to adjust it little bit get data for last event.
ContentResolver cr = getContentResolver();
Uri caluri = CalendarContract.Events.CONTENT_URI;
Uri atteuri = CalendarContract.Attendees.CONTENT_URI;
Cursor cur1, cur2;
String all = null;
try
{
cur1 = cr.query(caluri
, new String[]{ Events.CALENDAR_ID, Events._ID, Events.TITLE, Events.DESCRIPTION, Events.DTSTART, Events.DTEND, Events.EVENT_LOCATION }
, null, null, null);
if (cur1 != null)
{
while (cur1.moveToNext())
{
String event_Title = cur1.getString(cur1.getColumnIndex(Events.TITLE));
String event_Desc = cur1.getString(cur1.getColumnIndexOrThrow(Events.DESCRIPTION));
Date event_Start = new Date(cur1.getLong(cur1.getColumnIndex(Events.DTSTART)));
Date event_end = new Date(cur1.getLong(cur1.getColumnIndex(Events.DTEND)));
String event_loc = cur1.getString(cur1.getColumnIndex(Events.EVENT_LOCATION));
String all_attendee = null;
String all_Emails = null;
String cal_ID = cur1.getString(cur1.getColumnIndex(Events.CALENDAR_ID));
String event_ID = cur1.getString(cur1.getColumnIndex(Events._ID));
cur2 = cr.query(atteuri, new String[]{ Attendees.ATTENDEE_NAME, Attendees.ATTENDEE_EMAIL }
, Attendees.EVENT_ID + "=" + event_ID, null, null);
if (cur2 != null)
{
while (cur2.moveToNext())
{
String attendee_name = cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_NAME));
String attendee_Email = cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_EMAIL));
all_attendee += "\n" + attendee_name;
all_Emails += "\n" + attendee_Email;
}
cur2.close();
}
all += "Event title: " + event_Title + "\n"
+ "Event Description: " + event_Desc + "\n"
+ "Event Start: " + event_Start + "\n" + "Events End: "
+ event_end + "\n" + "Event Location: " + event_loc
+ "\n" + "Attendees: " + "\n" + all_attendee + "\n"
+ "Emails: " + "\n" + all_Emails + "\n";
}
cur1.close();
}
System.out.println("My log--------" + all);

get contact event details in android

I need to fetch the all events of all contacts in my android application.
Can anyone help me on this?
what I need to place the Uri for the below..
Cursor events = getContentResolver().query(xxxx,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
Try this method, it should work. Do the Log.d(tag, "Output here"); to test your output, but it should work. It does here.
public void getEvent(String contactId)
{
final String[] projection = new String[] {
Event.CONTACT_ID,
Event.START_DATE,
//Event.TYPE,
Event.LABEL
};
final String filter = Data.MIMETYPE + " = ? AND " + Data.CONTACT_ID + " = ? ";
final String parameters[] = {Event.CONTENT_ITEM_TYPE, contactId};
Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
projection,
filter,
parameters,
null);
if(cursor.moveToFirst())
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
final String contact_id = cursor.getString(cursor.getColumnIndex(Event.CONTACT_ID));
final String startDate = cursor.getString(cursor.getColumnIndex(Event.START_DATE));
//final String type = cursor.getString(cursor.getColumnIndex(Event.TYPE));
final String label = cursor.getString(cursor.getColumnIndex(Event.LABEL));
}
}
}

Android get calendar event in tablet

I am using below code to get calendar events in my application. It's working fine in Android phones but when I try this code on Android tablet, my application crashes. So I don't know exactly what is the problem and why it is not working on tablets.
public void syncCalander() {
try {
nameValues = new ArrayList<NameValuePair>();
StringBuffer calbuffers;
int cnt = 1;
StringBuffer calbufferimeis = new StringBuffer();
ContentResolver contentResolver = getApplicationContext()
.getContentResolver();
final Cursor cursor = contentResolver.query(
Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null,
null, null);
if (cursor.getCount() == 0) {
} else {
HashSet<String> calendarIds = new HashSet<String>();
CalendarModel calModel = new CalendarModel();
CalendarModel.CALENDERLIST.add(calModel);
int val = cursor.getCount();
Log.i("=============total event============>", "." + val);
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
calModel.setCalendarEvent(displayName);
CalendarModel.CALENDERLIST.add(calModel);
Log.i("--------Display Name----------", "" + "Id: " + _id
+ " Display Name: " + displayName + " Selected: "
+ selected);
calendarIds.add(_id);
Log.i("============celenderIDs==========>", "."
+ calendarIds);
}
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse(
"content://com.android.calendar/instances/when")
.buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now
- DateUtils.WEEK_IN_MILLIS);
ContentUris.appendId(builder, now
+ DateUtils.WEEK_IN_MILLIS);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay" },
"Calendars._id=" + id, null,
"startDay ASC, startMinute ASC");
Log.i("============cursor size===========>", "."
+ eventCursor.getCount());
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3)
.equals("0");
calModel.setCalendarDate(begin.toString());
CalendarModel.CALENDERLIST.add(calModel);
Log.i("-----Title--------", "Title: " + title
+ " Begin: " + begin + " End: " + end
+ " All Day: " + allDay);
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String date = formatter.format(begin);
int callength = CalendarModel.CALENDERLIST.size();
calbuffers = new StringBuffer();
calbuffers.append("{\"Calenderevent\":\"" + title
+ "\"," + "\"Calenderdate\":\"" + date + "\"}");
calbuffers.append(",");
calbufferimeis.append(calbuffers);
}
eventCursor.close();
}
}
cursor.close();
} catch (Exception e) {
}
}
i have use
content://calendar/calendars
instead of
content://com.android.calendar/calendars
for the android tablet applications

Categories

Resources