How to read and edit Android calendar events using the new Android 4.0 Ice Cream Sandwich API?

前端 未结 6 2139
醉梦人生
醉梦人生 2020-11-28 22:13

We are trying to show user the Ice cream Sandwich calendar view, when they want to add a new event. We can only test this in emulator.

The other problem is that we c

相关标签:
6条回答
  • 2020-11-28 22:39
    public static ArrayList<String> readCalendarEvent(Context context) {
            Cursor cursor = context.getContentResolver()
                    .query(
                            Uri.parse("content://com.android.calendar/events"),
                            new String[] { "calendar_id", "title", "description",
                                    "dtstart", "dtend", "eventLocation" }, null,
                            null, null);
            cursor.moveToFirst();
            // fetching calendars name
            String CNames[] = new String[cursor.getCount()];
    
            // fetching calendars id
            nameOfEvent.clear();
            startDates.clear();
            endDates.clear();
            descriptions.clear();
            Log.d("cnameslength",""+CNames.length);
            if (CNames.length==0)
            {
             Toast.makeText(context,"No event exists in calendar",Toast.LENGTH_LONG).show();
            }
            for (int i = 0; i < CNames.length; i++) {
    
                nameOfEvent.add(cursor.getString(1));
                startDates.add(getDate(Long.parseLong(cursor.getString(3))));
                endDates.add(getDate(Long.parseLong(cursor.getString(4))));
                descriptions.add(cursor.getString(2));
                CNames[i] = cursor.getString(1);
                cursor.moveToNext();
                Log.d("datacur",""+nameOfEvent.get(i));
                Log.d("datacur",""+startDates.get(i));
                Log.d("datacur",""+endDates.get(i));
                Log.d("datacur",""+descriptions.get(i));
                String filename=nameOfEvent.get(i)+"::"+startDates.get(i)+"::"+endDates.get(i)+"::"+descriptions.get(i);
                generateNoteOnSD(context,nameOfEvent.get(i),filename);
    
            }
            return nameOfEvent;
        }
    
    
    
    
    
    public static void generateNoteOnSD(Context context, String sFileName, String sBody) {
            try {
                File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) {
                    root.mkdirs();
                }
                File gpxfile = new File(root, sFileName);
                FileWriter writer = new FileWriter(gpxfile);
                writer.append(sBody);
                writer.flush();
                writer.close();
                Toast.makeText(context, "Successfully Backup Created", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
  • 2020-11-28 22:41

    I used the following code to read all the events in Calendar.

    public boolean isEventInCal(Context context, String cal_meeting_id) {
    
        Cursor cursor = context.getContentResolver().query(
        Uri.parse("content://com.android.calendar/events"),
                new String[] { "_id" }, " _id = ? ",
                new String[] { cal_meeting_id }, null);
    
        if (cursor.moveToFirst()) {
            // will give all events
            return true;
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-11-28 22:44

    Make sure,you are not using 'visibilty' for ICS and JellyBean devices (apiLevel>=14)

    Try this -

    ContentValues values= new ContentValues();
    int apiLevel = android.os.Build.VERSION.SDK_INT;
                if(apiLevel<14)
                values.put("visibility", 0);
    

    Use visibility only if device version is less than 14(ICS)

    0 讨论(0)
  • 2020-11-28 22:49

    I have creted following Method to handle the flexibility of TIMEZONE

    // Converting TimeZone in to GMT to save upon local Db to avoid // Controversy Over Server

    private String convertDateTimeZone(long originalDate) {
            String newDate = "";
            Date date = new Date(originalDate);
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            Date parsed = null;
            try {
                parsed = formatter.parse(formatter.format(date).toString());
                TimeZone tz = TimeZone.getTimeZone("GMT");
                SimpleDateFormat destFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                destFormat.setTimeZone(tz);
    
                newDate = destFormat.format(parsed);
            } catch (Exception e) {
            }
            return newDate;
        }
    
    0 讨论(0)
  • 2020-11-28 22:51

    Here's code that will let you add an event directly:

    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.net.Uri;
    import android.provider.CalendarContract;
    
    import java.util.Calendar;
    
    // Construct event details
    long startMillis = 0;
    long endMillis = 0;
    Calendar beginTime = Calendar.getInstance();
    beginTime.set(2012, 9, 14, 7, 30);
    startMillis = beginTime.getTimeInMillis();
    Calendar endTime = Calendar.getInstance();
    endTime.set(2012, 9, 14, 8, 45);
    endMillis = endTime.getTimeInMillis();
    
    // Insert Event
    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    TimeZone timeZone = TimeZone.getDefault();
    values.put(CalendarContract.Events.DTSTART, startMillis);
    values.put(CalendarContract.Events.DTEND, endMillis);
    values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
    values.put(CalendarContract.Events.TITLE, "Walk The Dog");
    values.put(CalendarContract.Events.DESCRIPTION, "My dog is bored, so we're going on a really long walk!");
    values.put(CalendarContract.Events.CALENDAR_ID, 3);
    Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
    
    // Retrieve ID for new event
    String eventID = uri.getLastPathSegment();
    

    You'll need the CALENDAR_ID, so here's how to query the list of calendars:

    Uri uri = CalendarContract.Calendars.CONTENT_URI;
    String[] projection = new String[] {
           CalendarContract.Calendars._ID,
           CalendarContract.Calendars.ACCOUNT_NAME,
           CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
           CalendarContract.Calendars.NAME,
           CalendarContract.Calendars.CALENDAR_COLOR
    };
    
    Cursor calendarCursor = managedQuery(uri, projection, null, null, null);
    

    You'll need to request the android.permission.READ_CALENDAR permission for all of this to work.

    If you want to avoid having to request permissions, you can also ask the Calendar app to create a new event on your behalf by using an Intent:

    Intent intent = new Intent(Intent.ACTION_INSERT)
             .setType("vnd.android.cursor.item/event")
             .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
             .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
             .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY , false) // just included for completeness
             .putExtra(Events.TITLE, "My Awesome Event")
             .putExtra(Events.DESCRIPTION, "Heading out with friends to do something awesome.")
             .putExtra(Events.EVENT_LOCATION, "Earth")
             .putExtra(Events.RRULE, "FREQ=DAILY;COUNT=10") 
             .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
             .putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE)
             .putExtra(Intent.EXTRA_EMAIL, "my.friend@example.com");
    startActivity(intent);
    
    0 讨论(0)
  • 2020-11-28 22:51

    You can use the following code to setup the timezone and it works for me

    TimeZone timeZone = TimeZone.getDefault();
    values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
    
    0 讨论(0)
提交回复
热议问题