0

I want to create calendar. It is working. But if Android version +4.0. it isn't work. I know that I need use content-providers, but I don't know how. I want that calendar is working in all versions Android. How can I do it?

   private void AddCalendar(int years,int months,int days,int hours,int minutes){
        try{
        // get calendar
        Calendar cal = Calendar.getInstance();     
        Uri EVENTS_URI = Uri.parse("content://com.android.calendar/events");
        ContentResolver cr = getContentResolver();

        Calendar start = Calendar.getInstance();
        start.set(years, months, days, hours, minutes, 0);

        Calendar end = Calendar.getInstance();
        end.set(years, months, days, hours + 1, minutes, 0);

        long startTime = start.getTimeInMillis();       
        long endTime = end.getTimeInMillis();

        // event insert
        ContentValues values = new ContentValues();
        values.put("calendar_id", 1);
        values.put("title", editText1.getText().toString());
        values.put("allDay", 0);
        values.put("dtstart", startTime); 
        values.put("dtend", endTime); 
        values.put("description", editText2.getText().toString());
        values.put("visibility", 0);
        values.put("hasAlarm", 1);
        Uri event = cr.insert(EVENTS_URI, values);

        // reminder insert
        Uri REMINDERS_URI = Uri.parse("content://com.android.calendar/reminders");
        values = new ContentValues();
        values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
        values.put( "method", 1 );
        values.put( "minutes", 10 );
        cr.insert( REMINDERS_URI, values );

        }catch (Exception e){
            Toast.makeText(getApplicationContext(), 
                    R.string.calendar, Toast.LENGTH_LONG).show();
        }

        }
user1468102
  • 391
  • 5
  • 16

2 Answers2

1

Calendar Api has changed in 4.0+. You can use the new Calendar Intent api (this is the recommended method) or modify your event to fit with the new api:

values.add("eventTimezone","00"); remove the "visibility" key/value, it's not accepted anymore.

You should print the exception in your ExceptionCatcher, it is quite descriptive.

alaeri
  • 344
  • 3
  • 16
0

Here it is answered and working!

But change the code to:

values.put(CalendarContract.Events.CALENDAR_ID, 1);

1 instead of 3 in order to select the default calendar.

But you can't have the same code for all android versions! You will need to make 2 different apps.One for android 4+ and one for android<4

oikonomopo
  • 4,025
  • 7
  • 44
  • 73