Delete single occurrence in google calendar - android

I want to delete a single occurrence of a repeated event. This is my code:
private void handleActionDelete(long event, long occurrence) {
final ContentResolver contentResolver = getContentResolver();
Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(eventsUriBuilder, Long.MIN_VALUE);
ContentUris.appendId(eventsUriBuilder, Long.MAX_VALUE);
Uri eventsUri = eventsUriBuilder.build();
Cursor cursor;
String[] projection;
projection = new String[]{CalendarContract.Instances.BEGIN};
String selection = "Instances." + CalendarContract.Instances._ID + " = ? AND " + CalendarContract.Instances
.EVENT_ID + " = ?";
String[] selArgs = new String[]{Long.toString(occurrence), Long.toString(event)};
cursor = getContentResolver().query(eventsUri, projection, selection, selArgs, null);
if (cursor == null) {
return;
}
if (cursor.getCount() == 0) {
cursor.close();
return;
}
cursor.moveToFirst();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, cursor.getLong(cursor.getColumnIndex
(CalendarContract.Instances.BEGIN)));
values.put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED);
Uri uri = Uri.withAppendedPath(CalendarContract.Events.CONTENT_EXCEPTION_URI, String.valueOf(event));
cursor.close();
try {
contentResolver.insert(uri, values);
} catch (Exception ignored) {
}
}
I already checked all other similar problems on stackoverflow but I didn't find any solution, maybe it's something related to my code, I hope someone can review it.

if you use com.google.api.services.calendar.Calendar I suppose you already have id of the event you want to delete
the answer is right there in the documentation and states (I've copied the exact snippet from doc):
// Initialize Calendar service with valid OAuth credentials
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credentials)
.setApplicationName("applicationName").build();
// Delete an event
service.events().delete('primary', "eventId").execute();

Related

Android set Custom ringtone for user defined number

I am writing code for setting custom ringtone in android. Took help from other answers in stackoverflow. Here is the code.
private void setContactRingtone(String number) {
final Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// The columns used for `Contacts.getLookupUri`
final String[] projection = new String[]{
ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY
};
// Build your Cursor
final Cursor data = getContentResolver().query(lookupUri, projection, null, null, null);
data.moveToFirst();
try {
// Get the contact lookup Uri
final long contactId = data.getLong(0);
final String lookupKey = data.getString(1);
final Uri contactUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
if (contactUri == null) {
// Invalid arguments
return;
}
File file = new File(this.getFilesDir() + File.separator + "ringtone.mp3");
final String value = Uri.fromFile(file).toString();
final ContentValues values = new ContentValues(1);
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, value);
getContentResolver().update(contactUri, values, null, null);
Toast.makeText(getApplicationContext(), "Done!!!!!!!!!!!", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// Don't forget to close your Cursor
data.close();
}
}
The code is not assigning the user defined ringtone to the contact. There are no exceptions generated.
SO the problem was in android 10 asset folder is accessible through inputstream.Referred this answer
Here we create a temporary file and write to external storage. And then read that file.

Android, media scan doesn't generate thumbnails?

I have image files which don't have thumbnails. (imported from my external carmera using NFC)
I want to create thumbnails for my image picker view. (has to be fast)
At this moment, I'm not even sure "MEDIA SCAN" means "generating thumbnail" or what.
I tried to scan file using mMediaScannerConnection.scanFile(mPath, null);
onScanCompleted gets called and I try to get thumbnail using the following two version of functions.
I get null thumbnailPath for both functions, I don't get why..
private String getThumbnailPath(long imageId) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = MediaStore.Images.Thumbnails.queryMiniThumbnail(cr, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
private String getThumbnailPath2( long imageId ){
// http://wikicloud.blogspot.kr/2010/10/scanfile.html
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Thumbnails.IMAGE_ID + "= ?" , new String[]{String.valueOf(imageId)}, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
-- edit --
Here's how I try to get thumbnails.
first create a mapping from image-id to thumbnail-path.
protected Map getThumbnailPathFromDB() {
Map result = new HashMap();
Cursor thumbCursor = null;
thumbCursor = getContentResolver().query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
null,
null,
null, null);
if (thumbCursor.moveToFirst()) {
do {
String path = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.MediaColumns.DATA));
long imageId = thumbCursor.getLong(thumbCursor
.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID));
result.put(new Long(imageId), path);
} while(thumbCursor.moveToNext());
}
thumbCursor.close();
return result;
next I iterate all images and try to find thumbnails from the mapping I created above
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(
Images.Media.EXTERNAL_CONTENT_URI, null,
null, null, Images.ImageColumns.DATE_MODIFIED + " DESC");
//thumbnailPathList is the mapping I created above, imageId is the id of image obtained from the cursor
String thumbnailPath = thumbnailPathList.get(new Long(imageId));
// thumbnailPath are occasionally null here!,
I tested my code on about 10 devices.
They all have images which I can't find thumbnails for.

Delete only incoming call in Call Logs in android

Is it possible to delete only incoming calls from the call log list?
If so how?
I am able to delete all of them easily but not sure how to delete only incoming calls?
Can somebody help me out with this?
Thanks!
In CallLog provider database, android.provider.CallLog.Calls.TYPE ("type") column will have value
android.provider.CallLog.Calls.INCOMING_TYPE (1) for an incoming call record.
Use below method with condition type = 1
public void delete(final String id, final String number) {
Uri uri = Uri.parse("content://call_log/calls");
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(uri, null, "and type = 1 and _id" + "=?", new String[] { "" + id }, null);
if (c != null && c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("_id"));
String pnumber = c.getString(c.getColumnIndex("NUMBER"));
if (id.equals(pid) && number.equals(pnumber)) {
context.getContentResolver().delete(CallLog.Calls.CONTENT_URI, CallLog.Calls._ID + " = ?", new String[] { id });
}
} while (c.moveToNext());
}
}

Getting calendar events in android 4.0 and above

I am new to the android development. I am working on calender application where i need to add/delete and get all events in between the date range. I have add and delete the events successufully but problem is when i am getting the calender events in between the date range. I am getting the calender events but when i go to SPlanner i can see those events are not added in the calender as i have already deleted them. I do not know from where i am getting those events.Please suggest. Here is the code i have written to get the calender events:-
public void onGetEvent (final String fullCallbackName, String title,String startDate,String endDate) throws JSONException
{
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final ArrayList<JSONObject> calEvents = new ArrayList();
if(calEvents.size() !=0)
{
calEvents.clear();
}
ContentResolver contentResolver = getContentResolver();
String selection = "((dtstart >= "+(dateFormat.parse(startDate).getTime())+") AND (dtend <= "+(dateFormat.parse(endDate).getTime())+"))";
Cursor cursor = contentResolver.query(Uri.parse(getCalendarUriBase() + "events"),
(new String[] { "_id", "title", "dtstart","dtend","eventLocation","description"}), selection, null, null);
Log.e("cursor.getCount before:","callbackFuncName:" + cursor.getCount());
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Log.e("cursor.getCount before:","callbackFuncName:" + displayName);
String[] separated = displayName.split(":");
if(separated[0]!= null && title.equals(separated[0]))
{
JSONObject dictionary = new JSONObject();
String dstart = dateFormat.format(new Date(Long.parseLong(cursor.getString(2))));//cursor.getString(2);
String dEnd = dateFormat.format(new Date(Long.parseLong(cursor.getString(3))));//cursor.getString(3);
String eventlocation = cursor.getString(4);
String description = cursor.getString(5);
dictionary.put("identifier", _id);
dictionary.put("title", displayName);
dictionary.put("startDate", dstart);
dictionary.put("endDate", dEnd);
dictionary.put("venue", eventlocation);
dictionary.put("notes", description);
calEvents.add(dictionary);
}
}
if(fullCallbackName != null && !fullCallbackName.equals(""))
{
runOnUiThread(new Runnable() {
public void run()
{
webView.loadUrl("javascript:"+fullCallbackName+" ("+calEvents+")") ;
}
});
}
}
catch(Exception e)
{
Log.e("string", e.toString());
}
}
}
code for getting the calender DB is:-
private String getCalendarUriBase() {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor cursor = null;
try {
cursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (cursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
cursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (cursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
Log.d("Sandeep",
calendarUriBase);
// managedCursor.close();
return calendarUriBase;
}
With your query you will see deleted events because they are still in the database (for being able to sync the deletion whenever the next sync is due). That's what the DELETED column is for.
To find all events between a start and end date use the Instances class of the CalendarContract API as in the code below. This code returns only visible events!
I've written a blog post about the CalendarContract content provider detailing this and other stuff.
long begin = // starting time in milliseconds; for you probably cursor.getLong(2)
long end = // ending time in milliseconds; cursor.getLong(3)
String[] proj =
new String[]{
Instances._ID,
Instances.TITLE,
Instances.BEGIN,
Instances.END,
Instances.EVENT_LOCATION,
Instances.DESCRIPTION,
Instances.EVENT_ID};
Cursor cursor =
Instances.query(getContentResolver(), proj, begin, end);
if (cursor.getCount() > 0) {
// do your JSON thing
}

Query Android contact to get ACCOUNT_TYPE and ACCOUNT_NAME

I am able to obtain a list of contacts and their basic information like: name. phones, emails, ims, notes, organizations for backup purposes by using ContactsContract.Contacts.CONTENT_URI for a list of Contacts and other specific URIs for different information type.
I need, in order to fully restore all the information two more fields:
ContactsContract.RawContacts.ACCOUNT_TYPE
ContactsContract.RawContacts.ACCOUNT_NAME
Can anyone guide me how to obtain this info, knowing the Contact Id from ContactsContract.Contacts.CONTENT_URI ?
Thank you
public ContactAccount getContactAccount(Long id,ContentResolver contentResolver) {
ContactAccount account = null;
Cursor cursor = null;
try {
cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.CONTACT_ID +"=?",
new String[]{String.valueOf(id)},
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
account = new ContactAccount();
account.setAccountName(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
account.setAccountType(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
cursor.close();
}
} catch (Exception e) {
Utils.log(this.getClass().getName(), e.getMessage());
} finally{
cursor.close();
}
return(account);
}
The above answer is perfect if you are looking for account information using the contactID column. But, often information is stored using rawContactID. So, if you want to access account information for a raw-contact-id then you can use this method below.
The key difference is that I am using the _ID column from the rawContacts table. This maps to the rawContactID that you will see in other tables
public int updateAccountInfoForContactData(String rawContactID) {
int accountPos = 0;
Cursor cursor = null;
String accountName = null;
String accountType = null;
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI;
String[] syncColumns = new String[] {
ContactsContract.RawContacts.ACCOUNT_NAME,
ContactsContract.RawContacts.ACCOUNT_TYPE,
};
String whereClause = ContactsContract.RawContacts._ID +"=?";
String[] whereParams = new String[]{String.valueOf(rawContactID)};
//Uri rawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, longContactID);
try {
cursor = mContext.getContentResolver().query(
rawContactUri,
syncColumns,
whereClause,
whereParams,
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME) >= 0) {
accountName = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
}
if(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE) >= 0) {
accountType = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
}
cursor.close();
cursor = null;
}
} catch (Exception e) {
Log.d(TAG, "getting account info failed");
} finally{
if(cursor != null) {
cursor.close();
}
cursor = null;
}
return(accountPos);
}

Categories

Resources