Baccega Andrea Blog

The future is web3.0

Posted on by veke87


Since i started developing applications for android i noticed there were some undocumented apis. Google does reccomend to not use these apis but since there are no "other nice ways" to achieve some tasks sometimes they are useful ( but still unreccomended)

It's the case of the Google Calendar Apis. Out there you can find a lot of docs about these undocumented & unsupported apis but you'll get some troubles if google decides to change them.

For example if you want to add an "event" to the calendar programmatically you can follow the snippet below which is SDK proof. In fact i did ( It's not refactored for better reading ) write some code that would work on Sdk from 1.5 to 2.2 ( aka Froyo ) solving the provider issue on froyo and above.

/**
 * Adds the event to a calendar. It lets the user choose the calendar
 * @param ctx Context ( Please use the application context )
 * @param title title of the event
 * @param dtstart Start time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 * @param dtend End time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 */
private static void addToCalendar(Context ctx, final String title, final long dtstart, final long dtend) {
    final ContentResolver cr = ctx.getContentResolver();
    Cursor cursor ;
    if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
        cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
    else
        cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
    if ( cursor.moveToFirst() ) {
        final String[] calNames = new String[cursor.getCount()];
        final int[] calIds = new int[cursor.getCount()];
        for (int i = 0; i < calNames.length; i++) {
            calIds[i] = cursor.getInt(0);
            calNames[i] = cursor.getString(1);
            cursor.moveToNext();
        }
 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setSingleChoiceItems(calNames, -1, new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ContentValues cv = new ContentValues();
                cv.put("calendar_id", calIds[which]);
                cv.put("title", title);
                cv.put("dtstart", dtstart );
                cv.put("hasAlarm", 1);
                cv.put("dtend", dtend);
 
                Uri newEvent ;
                if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
                    newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
                else
                    newEvent = cr.insert(Uri.parse("content://calendar/events"), cv);
 
                if (newEvent != null) {
                    long id = Long.parseLong( newEvent.getLastPathSegment() );
                    ContentValues values = new ContentValues();
                    values.put( "event_id", id );
                    values.put( "method", 1 );
                    values.put( "minutes", 15 ); // 15 minutes
                    if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
                        cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
                    else
                        cr.insert( Uri.parse( "content://calendar/reminders" ), values );
 
                }
                dialog.cancel();
            }
 
        });
 
        builder.create().show();
    }
    cursor.close();
}

Hope it helps to solve the problem about google calendar in froyo :)

Reference to the CP: Xda

Posted on by veke87 | Posted in Android, Development | Tagged , ,


  • Saif

    Hi,
    It worked, i have forgotten to add read and write premission in manifest. Thanks a lot. Its really very nice tutorial.

  • Jack

    works only for me if i change
    …(Build.VERSION.SDK) == 8
    to
    …(Build.VERSION.SDK) >= 8

    (2 times)

  • Daniel

    Hi,
    Ive tried your example with a few tweaks, but I still can’t make it work. I’ve tried it on my 2.3.7 android phone.

    Hope you can help me…

    public class LolActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /*
    Another way of adding events
    Calendar cal = Calendar.getInstance();
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType(“vnd.android.cursor.item/event”);
    intent.putExtra(“beginTime”, cal.getTimeInMillis());
    intent.putExtra(“allDay”, true);
    intent.putExtra(“rrule”, “FREQ=YEARLY”);
    intent.putExtra(“endTime”, cal.getTimeInMillis()+60*60*1000);
    intent.putExtra(“title”, “A Test Event from android app”);
    startActivity(intent);
    }
    */
    Calendar beginTime = Calendar.getInstance();
    beginTime.set(2011, 11, 15);
    Calendar endTime = Calendar.getInstance();
    endTime.set(2011, 11, 16);

    addToCalendar(this, “Titel paa test”, beginTime.getTimeInMillis(), endTime.getTimeInMillis());
    }
    public void addToCalendar(Context ctx, final String title, final long dtstart, final long dtend) {
    final ContentResolver cr = ctx.getContentResolver();

    Cursor cursor ;
    if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
    cursor = cr.query(Uri.parse(“content://com.android.calendar/calendars”), new String[]{ “_id”, “displayname” }, null, null, null);
    else
    cursor = cr.query(Uri.parse(“content://calendar/calendars”), new String[]{ “_id”, “displayname” }, null, null, null);
    if ( cursor.moveToFirst() ) {
    final String[] calNames = new String[cursor.getCount()];
    final int[] calIds = new int[cursor.getCount()];
    for (int i = 0; i = 8 )
    newEvent = cr.insert(Uri.parse(“content://com.android.calendar/events”), cv);
    else
    newEvent = cr.insert(Uri.parse(“content://calendar/events”), cv);
    if (newEvent != null) {
    // Long.parseLong( newEvent.getLastPathSegment() );
    }

    dialog.cancel();
    }

    });

    builder.create().show();
    }

    }

    }

  • sidhLazy

    Good Tutorial. Thanks.

    Event gets added to calendar. however when i try to edit, i get a force close error on 2.3.7

    ————–log———
    11-22 17:06:22.740: E/AndroidRuntime(5250): Caused by: java.lang.NullPointerException
    11-22 17:06:22.740: E/AndroidRuntime(5250): at java.util.TimeZone.getTimeZone(TimeZone.java:286)
    11-22 17:06:22.740: E/AndroidRuntime(5250): at com.android.calendar.TimezoneAdapter.showInitialTimezones(TimezoneAdapter.java:255)
    11-22 17:06:22.740: E/AndroidRuntime(5250): at com.android.calendar.TimezoneAdapter.(TimezoneAdapter.java:198)
    11-22 17:06:22.740: E/AndroidRuntime(5250): at com.android.calendar.EditEvent.onCreate(EditEvent.java:707)

  • Justin

    You should probably change:
    Integer.parseInt(Build.VERSION.SDK) == 8
    to
    Integer.parseInt(Build.VERSION.SDK) >= 8

    and line 40 should be:
    newEvent = cr.insert(Uri.parse(“content://calendar/events”), cv);

  • Pingback: Solar Power Monitor

  • Artz

    @veke87 : Can you give us a full source code  ????

  • Andrea Baccega

    Hello Artz, I think all the sourcecode you need is there. Do you’ve any troubles with it ?

    Cheers

  • Andrea Baccega

    Thanks Justin, I patched the code with your mods.

  • Lakshmikanthsm

    HI,
    Greetings of the day,

    as a new developer in android platform im stuck in create a calender app with many events.

    can anybody please help me to create calendar and add the multiple events to that calendar.

    waiting for positive reply.

    or any use full links or code pls share with me