Actually I have two java classes of which one is an activity class. Now from that activity class, I want to call a function of second class which is not in an activity class. So all works fine but when I use SharedPreferences inside that function it shows me an error Unable to start activity ComponentInfo java.lang.NullPointerException. Please, anyone help.
code for first java file:
public class SplashScreen extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
CycleManager.getSingletonObject().test();//call functions of another class
}
}
code for second java file:
public class CycleManager
{
private static CycleManager cycleMangrObject;
private CycleManager() {
onInitialization();
//Compute averages using data loaded from register
ComputeAverages();
}
public static synchronized CycleManager getSingletonObject() {
if (cycleMangrObject == null) {
cycleMangrObject = new CycleManager();
}
return cycleMangrObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public void test()
{
SharedPreferences preferences1 =getSharedPreferences("myPreferences", 0);
}
public void setAlertOnDevice(){
//Delete data
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
int id = 1; // calendar entry ID
ContentResolver cr = getContentResolver();
EVENTS_URI= ContentUris.withAppendedId(EVENTS_URI, id);
cr.delete(EVENTS_URI, "calendar_id=1", null);
Resources res=getResources();
//set Alerts in device calendar
Date dtStartDate = CycleManager.getSingletonObject().getStartDate();
boolean bDeleteAndReturn = false;
Calendar cal = Calendar.getInstance();
if (dtStartDate.getTime() == CycleManager.getSingletonObject().getDefaultDate().getTime())
{
bDeleteAndReturn = true;
dtStartDate = cal.getTime();
}
getOffsetsForCycleStages(CycleManager.getSingletonObject().iAvgCycleTime);
if(bDeleteAndReturn==false)
{
if (CycleManager.getSingletonObject().bNextCycleAlert && iStart>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iStart);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_start);
String strDescription=res.getString(R.string.alert_start_msg);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
if (CycleManager.getSingletonObject().bSafeAlert)
{
if (iSafe1>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iSafe1);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_safe);
String strDescription=res.getString(R.string.alert_safe_msg) + " " + new Integer(iUnsafe1-iSafe1-1);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
if (iSafe2>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iSafe2);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_safe);
String strDescription=res.getString(R.string.alert_safe_msg) + " " + new Integer(CycleManager.getSingletonObject().iAvgCycleTime-iSafe2-1);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
}
if (CycleManager.getSingletonObject().bUnsafeAlert)
{
if (iUnsafe1>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iUnsafe1);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_unsafe);
String strDescription=res.getString(R.string.alert_unsafe_msg) + " " + new Integer(iFertile-iUnsafe1-1);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
if (iUnsafe2>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iUnsafe2);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_unsafe);
String strDescription=res.getString(R.string.alert_unsafe_msg) + " " + new Integer(iSafe2-iUnsafe2-1);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
}
if (CycleManager.getSingletonObject().bFertileAlert && iFertile>0)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iFertile);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_fertile);
String strDescription=res.getString(R.string.alert_fertile_msg) + " " + new Integer(iUnsafe2-iFertile-1);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
if (CycleManager.getSingletonObject().bPMSAlert)
{
cal.setTime(dtStartDate);
cal.add(Calendar.DATE, iStart-7);
// ContentResolver cr = getContentResolver();
String str=res.getString(R.string.alert_pms);
String strDescription=res.getString(R.string.alert_pms_msg);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
cr.insert(EVENTS_URI, values);
}
}
}
private String getCalendarUriBase(Activity act){
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try
{
managedCursor = act.managedQuery(calendars, null, null, null, null);
}
catch (Exception e) {}
if (managedCursor != null)
{
calendarUriBase = "content://calendar/";
}
else
{
calendars = Uri.parse("content://com.android.calendar/calendars");
try
{
managedCursor = act.managedQuery(calendars, null, null, null, null);
}
catch (Exception e){}
if (managedCursor != null)
{
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Its not possible because the other class does't know there something called SharedPreference.. so
public void test(Context c)
{
SharedPreferences preferences1 =c.getSharedPreferences("myPreferences", 0);
}
and while calling
CycleManager.getSingletonObject().test(this);//call functions of another class
and again
c.getContentResolver().delete(EVENTS_URI, null, null);
CycleManager.getSingletonObject().test(this);
public void test(Context c)
{
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(c);
}
No you cannot use the Activity or Android functions in an ordinary simple java class. Since you can only use java library in that Simple Java Class
One possible solution is:
Create a public static SharedPreferences object in an activity and Create an object of SplashScreen like this:
public static SharedPreferences pref = null;
public static SplashScreen sp;
In onCreate of Splash Screen do this
sp = this;
In your java Class method do this
SplashScreen.pref = SplashScreen.sp.getSharedPreferences("my pref", 0);
Related
I'm using below code in Marshmellow device to add the event to the Calendar programmatically but it's not working. Any idea? I cannot see this event in the Calendar app.
long startMillis = 0;
long endMillis = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = null, endDate = null;
try{
startDate = simpleDateFormat.parse("2017-05-01 01:30:00");
startMillis = startDate.getTime();
endDate = simpleDateFormat.parse("2017-05-01 03:30:00");
endMillis = endDate.getTime();
}catch (ParseException e){
e.printStackTrace();
}
ContentResolver cr = this.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, "Hello Title");
values.put(CalendarContract.Events.DESCRIPTION, "Add events to Calendar");
values.put(CalendarContract.Events.CALENDAR_ID, 879);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
PS: It works if only one gmail account is synced with the calendar app.
Am also find so many solutions finally i got solution and successfully calendar event added with Schedule event.
Step -1 > Enable Google calnedar API From google console.
Step - 2 > Add the permission in Androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
Step =3 > Add library for checking Permissions in your .gradle
compile 'com.karumi:dexter:4.1.0'
Dexter.withActivity(YoutActivityName.this)
.withPermission(Manifest.permission.WRITE_CALENDAR)
.withListener(new PermissionListener()
{
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
try {
int calenderId = -1;
String calenderEmaillAddress = "sathishmicit2012#gmail.com";
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
CalendarContract.Calendars.NAME + "=? or " +
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
new String[]{calenderEmaillAddress, calenderEmaillAddress,
calenderEmaillAddress}, null);
if (cursor.moveToFirst()) {
if (cursor.getString(1).equals(calenderEmaillAddress)) {
calenderId = cursor.getInt(0);
}
}
long start2 = Calendar.getInstance().getTimeInMillis(); // 2011-02-12 12h00
long end2 = Calendar.getInstance().getTimeInMillis() + (4 * 60 * 60 * 1000); // 2011-02-12 13h00
String title = "This is my demo test with alaram with 5 minutes";
ContentValues cvEvent = new ContentValues();
cvEvent.put("calendar_id", calenderId);
cvEvent.put(CalendarContract.Events.TITLE, title);
cvEvent.put(CalendarContract.Events.DESCRIPTION, String.valueOf(start2));
cvEvent.put(CalendarContract.Events.EVENT_LOCATION, "Bhatar,Surat");
cvEvent.put("dtstart", start2);
cvEvent.put("hasAlarm", 1);
cvEvent.put("dtend", end2);
cvEvent.put("eventTimezone", TimeZone.getDefault().getID());
Uri uri = getContentResolver().insert(Uri.parse("content://com.android.calendar/events"), cvEvent);
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, 2);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALARM);
cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
Hello Calender ID is 879 you cant take it random. Calender ID must be from this URI content://com.android.calendar/calendars
int calenderId=-1;
String calenderEmaillAddress="xxx#gmail.com";
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME};
ContentResolver cr = activity.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
CalendarContract.Calendars.NAME + "=? or " +
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
new String[]{calenderEmaillAddress, calenderEmaillAddress,
calenderEmaillAddress}, null);
if (cursor.moveToFirst()) {
if (cursor.getString(1).equals(calenderEmaillAddress))
calenderId=cursor.getInt(0); //youre calender id to be insered in above your code
}
protected void addToCalendar()
{
final ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayName" }, null, null, null);
cursor.moveToFirst();
String[] calNames = new String[cursor.getCount()];
final int[] calIds = new int[cursor.getCount()];
Log.i("Cal Names Length", "Length of Cals:"+calNames.length);
Log.i("Names of calendar:", "Cal names:"+calNames.toString());
for (int i=0; i<calNames.length; i++)
{
calIds [i] = cursor.getInt(0);
calNames[i] = cursor.getString(1);
cursor.moveToNext();
Log.i("Calendar", "Cal_id:"+calIds[0]);
Log.i("Calendar", "Cal_Name:"+calNames[0]);
}
cursor.close();
ContentResolver cr = getContentResolver();
if(calIds.length > 0)
{
Log.i("in if condition", "Of calIds.length");
Calendar cal = Calendar.getInstance();
Date birth_date = null;
for (int i = 0; i < final_list.size(); i++)
{
obj = final_list.get(i);
String dateFromDB = obj.getmBirthday();
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
try
{
birth_date = parser.parse(dateFromDB);
}
catch (java.text.ParseException e)
{
e.printStackTrace();
}
// event insert
int cal_id = calIds[0];
ContentValues values = new ContentValues();
values.put("calendar_id", cal_id);
Log.i("Calendar", "Cal_ID:"+cal_id);
values.put("title", obj.getmName());
Log.i("Title", "Title:"+obj.getmName());
values.put("dtstart", birth_date.getTime());
values.put("dtend", birth_date.getTime() + 1800*1000);
values.put("duration", 1800*1000 );
values.put("description", "Birthday Reminder");
values.put("allDay", 1);
values.put("rrule", "FREQ=YEARLY");
values.put("visibility", 0);
values.put("hasAlarm", 1);
cr.insert(Uri.parse("content://com.android.calendar/events"), values);
}
}
}
I have used this method on button click. When I click on the button ArrayList of Events should be added to Default calendar of Android Device. But here in this code, I am unable to see the event that is added to Calendar. And I even think that entry is not being added to calendar.
Thank you.
This is what I use, and it works in my code
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", startDate.getTimeInMillis());
intent.putExtra("endTime", endDate.getTimeInMillis());
intent.putExtra("title", title);
activty.startActivity(intent);
The event is added to android calendar, but it's not checked to see if the same event is already there (possible duplicate of the event)
I facing a events details saving in android calendar from the long time. I am able to save the details in devices below android version 2.2.3 but for above it doesn't save to calendar. Here is my code:
Calendar cal = Calendar.getInstance();
Uri events = null;
if(getCalendarUriBase(this)!=null)
{
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
long eventdate1=Date.parse(“23/07/2012”);
long eventdate2=Date.parse((“23/07/2012”);
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title","Event 1");
values.put("allDay", 0);
values.put("dtstart", eventdate1); // event starts at 11 minutes from now
values.put("dtend", eventdate2); // ends 60 minutes from now
values.put("description", "Description 1");
values.put("eventLocation", "xyz");
values.put("visibility", 0);
values.put("hasAlarm", 1);
try{
try{
events = cr.insert(EVENTS_URI, values);
}catch (Exception e) {
// TODO: handle exception
return false;
}
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(events.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
******
Where I am missing something. Please help me on it.
I had a similar problem. I think the problem is in
values.put("visibility", 0);
I think that there is no column in database with that name. It's the same with column named transparency. I found it in some tutorials on the net
I need to be able to create an event in the Google Calendar from my Android app. I believe there is a Calendar API but I have never used it. I'm fairly new to Android development so I've found a few examples from browsing earlier and used the following code to try to update my Android Calendar.
public static boolean updateCalendar(Context context,String cal_Id,String eventId)
{
try{
Uri CALENDAR_URI = Uri.parse(CAL_URI+"events");
Cursor c = context.getContentResolver().query(CALENDAR_URI, null, null, null, null);
String[] s = c.getColumnNames();
if (c.moveToFirst())
{
while (c.moveToNext())
{
String _id = c.getString(c.getColumnIndex("_id"));
String CalId = c.getString(c.getColumnIndex("calendar_id"));
if ((_id==null) && (CalId == null))
{
return false;
}
else
{
if (_id.equals(eventId) && CalId.equals(cal_Id))
{
Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(_id));
context.getContentResolver().update(uri, null, null, null);// need to give your data here
return true;
}
}
}
}
}
finally
{
return true;
}
}
However when I run it the getColumnNames doesn't get called and the code jumps straight to the line context.getContentResolver().update(uri, null, null, null); and then exits.
I put a couple of test events in my Calendar, why is the code not picking them up?
use this to add event to calender to particular date and time
Uri event1;
long epoch;
long epoch1;
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
try
{
epoch = new java.text.SimpleDateFormat ("yyyy-MM-dd hh:mm").parse(YourStartDate+" "+YourStratTime).getTime();
//epoch=epoch;
Log.e("epoch",String.valueOf(epoch));
epoch1 = new java.text.SimpleDateFormat ("yyyy-MM-dd hh:mm").parse(YourStartDate+" "+YourEndDate).getTime();
//epoch1=epoch1;
Log.e("epoch1",String.valueOf(epoch1));
} catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
values.put("calendar_id", 1);
values.put("title", "Appoitment");
values.put("allDay", 0);
values.put("dtstart",epoch); // event starts at 11 minutes from now
values.put("dtend", epoch1 ); // ends 60 minutes from now
values.put("description", "Your consulting date and time ");
values.put("visibility", 0);
values.put("hasAlarm", 1);
if(EVENTS_URI!=null)
{
event1 = cr.insert(EVENTS_URI, values);
}
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event1.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
if(REMINDERS_URI!=null)
{
cr.insert( REMINDERS_URI, values );
}
getCalendarUroBase function:
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Note: As per Sample Date should be in yyyy-MM-dd, time should be in hh:mm formats
I am trying to add an event to the android calendar, and I specify that the event will be added to the gmail calendar in order to sync with the Google calendar automatically.
The problem is events added programmatically don't sync with Google calendar, but if I add it manual on the phone it does sync with Google calendar. I don't know why.
This is the code that I use to add the event:
ArrayList<MyCalendar> calendars = new ArrayList<MyCalendar>();
String[] projection = new String[] { "_id", "name" };
Uri calUri = getCalendarURI(false);
Cursor managedCursor = managedQuery(calUri, projection, "selected=1",
null, null);
String calName = null;
String calId = null;
if (managedCursor.moveToFirst()) {
int nameColumn = managedCursor.getColumnIndex("name");
int idColumn = managedCursor.getColumnIndex("_id");
do {
calName = managedCursor.getString(nameColumn);
calId = managedCursor.getString(idColumn);
calendars.add(new MyCalendar(Integer.parseInt(calId), calName));
} while (managedCursor.moveToNext());
}
Toast.makeText(getBaseContext(), calName + " " + calId,
Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance();
ContentValues event = new ContentValues();
event.put("calendar_id", 2);
event.put("title", "Test Event2");
event.put("description", "Hiii Buddy");
long startTime = cal.getTimeInMillis();
long endTime = cal.getTimeInMillis() + 60 * 60 * 1000;
event.put("dtstart", startTime);
event.put("dtend", endTime);
event.put("allDay", 0);
event.put("eventStatus", 1);// tentative 0, confirmed 1 canceled 2
event.put("visibility", 3);// default 0 confidential 1 private 2
// public 3
event.put("transparency", 0);// opaque 0 transparent 1
event.put("hasAlarm", 1); // 0 false, 1 true
Uri eventsUri = getCalendarURI(true);
Uri url = getContentResolver().insert(eventsUri, event);
So the event successfully added to calendar but it doesn't show up in the Google calendar at the web (don't sync) but if I add the event manually it does sync !!!
You can sync your event after adding it by this function,It's worked for me(in API 8 and later):
public static void syncCalendar(Context context, String calendarId) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
values.put(CalendarContract.Calendars.VISIBLE, 1);
cr.update(
ContentUris.withAppendedId(getCalendarUri(),
Long.parseLong(calendarId)), values, null, null);
}
Try this code to insert an event into the android calendar as well as google calendar:
ContentValues values = new ContentValues();
cal_id = String.valueOf(p1);
values.put("calendar_id", p1);
values.put("title", title1);
values.put("allDay", 0);
values.put("dtstart", settime);
values.put("dtend", cal.getTimeInMillis()+60*60*1000);
values.put("description", desc1);
values.put("visibility", 0);
values.put("transparency", 0);
values.put("hasAttendeeData", 1);
values.put("hasAlarm", 0);
event = cr.insert(EVENTS_URI, values);
event1=event;
dat1 = event.toString();
long id=-1;
if (event != null)
{
id = Long.parseLong(event.getLastPathSegment());
ContentValues values1 = new ContentValues();
values1.put("event_id", id);
values1.put("method", 1); //METHOD_ALERT
Uri reminder = Uri.parse(getCalendarUriBase(this) + "reminders");
this.getContentResolver().insert(reminder, values1);
if(s.length() > 0 || partmail.length() > 0)
{
//REQUIRES FOLLOWING CODE
This code is used to add the event sync'ed to the google calendar
ContentValues attendees = new ContentValues();
attendees.put("event_id", id);
attendees.put("attendeeEmail", partmail1);
attendees.put("attendeeRelationship", 2);//RELATIONSHIP_ATTENDEE
attendees.put("attendeeStatus", 3); //ATTENDEE_STATUS_INVITED
attendees.put("attendeeType", 1); //TYPE_REQUIRED
id1=(int)id;
alarmid = (int) id;
Uri attendeesUri = null;
if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
{
attendeesUri = Uri.parse("content://com.android.calendar/attendees");
}
else if(Integer.parseInt(Build.VERSION.SDK) < 8)
{
attendeesUri = Uri.parse("content://calendar/attendees");
}
this.getContentResolver().insert(attendeesUri, attendees);
Toast.makeText(this, "Task Scheduled Successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Could not create Task!", Toast.LENGTH_SHORT);
}
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", id);
values.put( "method", 1 );
values.put( "minutes", 0 );
cr.insert( REMINDERS_URI, values );
Get Calendar's Uri since it differs for API levels such as till 8, greater than 8 and greater than 11.
private String getCalendarUriBase(Context con) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// statement to print the stacktrace
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Use the google calender api provided here
The above reference is somewhat general as Android doesn’t provide an official API. So, another solution more android specific is An Android Tutorial–Programming with Calendar
which contains a working example too. Also, be careful at Permission Declaration like READ_CALENDAR , WRITE_CALENDAR