Showing posts with label Calendar. Show all posts
Showing posts with label Calendar. Show all posts

Monday, May 14, 2012

Set “date” with two ways: in Android ?


First Way:
If you are retrieving date directly from db then take it in String
Then check whether there that date is null or not.
Like shown below:
String strRequiredDate = ClassObject.getMyDate();
if(strExpirationDate != null)
{
String strDate;
SimpleDateFormat objDateFormat;
Date objDate;
objDateFormat = new SimpleDateFormat(“dd MMM yyyy HH:mm”);
objDateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
objDate = objDateFormat.parse(strRequiredDate);
strDate = DateFormat.getDateFormat(getApplicationContext()).format(objDate);
objDateFormat = new SimpleDateFormat(“hh:mm aaa”);
objDateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
strDate = strDate + “  ” + objDateFormat.format(objDate);
btnPickDateTime.setText(strDate);
btnPickDateTime.setVisibility(View.VISIBLE);
}
Output:
04/01/2013 09:35 AM

Second Way:
SimpleDateFormat formatter;
Date objDate = new Date();
//Date values
int year;
int dayOfMonth;
int monthOfYear;
//Time values
int hour;
int min;
year = objDatePicker.getYear() – 1900;
dayOfMonth = objDatePicker.getDayOfMonth();
monthOfYear = objDatePicker.getMonth();
hour = objTimePicker.getCurrentHour();
min = objTimePicker.getCurrentMinute();
objDate.setDate(dayOfMonth);
objDate.setMonth(monthOfYear);
objDate.setYear(year);
objDate.setHours(hour);
objDate.setMinutes(min);
_objExpiryDate = objDate;
formatter=new SimpleDateFormat(DATE_FORMAT);
btnPickDateTime.setText(formatter.format(objDate));
Where as objDatePicker is nothing but my DatePicker control to select the perticular date.
objTimePicker is nothing but my TimePicker control to select the perticular time.
Output:
4 Jan 2013 09:35

Tuesday, March 27, 2012

How to convert Date and Time in Millisecond in android?


public long dateConvertor(String date) throws ParseException {
Date currentpastDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("d MMM yyyy h:mm a");
currentpastDate = (Date) formatter.parse(date);


} catch (Exception E) {
E.printStackTrace();
}
return currentpastDate.getTime();
}

Monday, March 19, 2012

How to Launch Calendar application in android 3.1?


Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.android.calendar","com.android.calendar.LaunchActivity");
startActivity(intent);

Sunday, March 18, 2012

How to get list of calendars in android 4.0?


 // Get list of Calendars 


        ContentResolver contentResolver = ctx.getContentResolver();
        Log.d(MainActivity.TAG, "URI = " + CalendarContract.Calendars.CONTENT_URI);
        final Cursor cursor = contentResolver.query(CalendarContract.Calendars.CONTENT_URI,
        CALENDAR_QUERY_COLUMNS, null, null, null);
        Log.d(MainActivity.TAG, "cursor = " + cursor);
        while (cursor.moveToNext()) {
        final String _id = cursor.getString(0);
        final String displayName = cursor.getString(1);
        final Boolean selected = !cursor.getString(2).equals("0");
        final String accountName = cursor.getString(3);
        Log.d(MainActivity.TAG, "Found calendar " + accountName);
        calendarList.append(
        "Calendar: Id: " + _id + " Display Name: " + displayName + " Selected: " + selected + " Name " + accountName);
        }

How to add event,reminder in Android 2.3 Calendar through code?


First of all we need to get the calendar provider uri.........
if (Build.VERSION.SDK_INT >= 8 ) {
        l_eventUri = Uri.parse("content://com.android.calendar/events");
    } else {
        l_eventUri = Uri.parse("content://calendar/events");
    }
But below the getCalendarUriBase(this) method is already return to get URI.So no need to use above code.It is just for your understanding.


You'll also need to add these permission to your manifest for this method.........
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

/*
* A device may have more than one Calendar configure in it. So first,
* you must find out available calendar's name and their id.
 */
Cursor cursor = getContentResolver() .query(Uri.parse(getCalendarUriBase(this) ),new String[] { "calendar_id", "displayname" }, null,null, null);
cursor.moveToFirst();
// fetching calendars name
String CNames[] = new String[cursor.getCount()];
// fetching calendars id
int[] CalIds = new int[cursor.getCount()];
for (int i = 0; i < CNames.length; i++) {
CalIds[i] = cursor.getInt(0);
CNames[i] = cursor.getString(1);
cursor.moveToNext();
}



        // get calendar
        Calendar cal = Calendar.getInstance();     
        Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
        ContentResolver cr = getContentResolver();


        // event insert
        ContentValues values = new ContentValues();
        values.put("calendar_id",CalIds);
        values.put("title", "Reminder Title");
        values.put("allDay", 0);
        values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
        values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
        values.put("description", "Reminder description");
        //Event Id
        values.put("_id", scheduleId);  
        //0~ default; 1~ confidential; 2~ private; 3~ public
        values.put("visibility", 0);
        //0~ false; 1~ true
        values.put("hasAlarm", 1);
        //status: 0~ tentative; 1~ confirmed; 2~ canceled
        values.put("eventStatus", 1);
    //0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
        values.put("transparency", 0);
        Uri event = cr.insert(EVENTS_URI, values);


        // reminder insert
        Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "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 );



        // for deleting event
// getContentResolver().delete(path to the content, want to delete,
// CONDITION, ARGUMENTS);
        // CONDITION + ARGUMENTS work as where condition to find a particular
 event.

getContentResolver().delete(
Uri.parse(getCalendarUriBase(this)),
"calendar_id=? and description=? and eventLocation=? ",
new String[] { String.valueOf(CalIds[0]), "Birthday Party",
"Delhi" });


getCalendarUriBase(this) is the method which provides the ContentProvider uri of Android device base on versions...........which is given below....



 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;
    }








How to open Add Event screen of Android Calendar through Intent code?


I don't know about the other version's but it worked for android 2.3 and 3.0.........

 /*add an event through intent, this doesn't require any permission
          just send intent to android calendar*/



        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", false);
        intent.putExtra("rrule", "FREQ=DAILY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        intent.putExtra("allDay", 0);
    //status: 0~ tentative; 1~ confirmed; 2~ canceled
        intent.putExtra("eventStatus", 1);
    //0~ default; 1~ confidential; 2~ private; 3~ public
        intent.putExtra("visibility", 0);
    //0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
        intent.putExtra("transparency", 0);
    //0~ false; 1~ true
        intent.putExtra("hasAlarm", 1);
        intent.putExtra("eventLocation", "@home");
        try {
    startActivity(intent);
    } catch (Exception e) {
    Toast.makeText(this.getApplicationContext(), "Sorry, no compatible calendar is found!", Toast.LENGTH_LONG).show();
    }

Thursday, March 15, 2012

How to display Current Week in android List Activity?


When the program was written the date was 15 Mar 2012............so you will find the output below in screenshots....


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;


import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;


public class WeekDisplayActivity extends ListActivity {
ArrayList<String> dateStringArray=new ArrayList<String>();
// String[] dateStringArray;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListAdapter adapter = createAdapter();
        setListAdapter(adapter);
    }
    
    protected ListAdapter createAdapter()
    {
   
    Calendar c = Calendar.getInstance();


// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);


// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
dateStringArray.add(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}

    // Create a simple array adapter (of type string) with the test values
    ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dateStringArray);

    return adapter;
    }
}




Below is the output..............



How to manipulate date in Android such as various formats and add or subtract certain number of days ?



//Add certain number of days to Today
       
int myDays = 3;

       
final Calendar c = Calendar.getInstance();
       
c.add(Calendar.DATE, myDays);  // number of days to add
       
int newDate =     (c.get(Calendar.YEAR) * 10000) + 
                           
((c.get(Calendar.MONTH) + 1) * 100) + 
                           
(c.get(Calendar.DAY_OF_MONTH));


//Subtract certain number of days to Today
       
int myDays = 3;

       
final Calendar c = Calendar.getInstance();
       
c.add(Calendar.DATE, (myDays * -1));  // number of days to subtract
       
int newDate =     (c.get(Calendar.YEAR) * 10000) + 
                           
((c.get(Calendar.MONTH) + 1) * 100) + 
                           
(c.get(Calendar.DAY_OF_MONTH));


//Change date format from yyyyMMdd to MM/dd/yy
       
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
           
Date date = null;
           
try {
               
date = df.parse(inputDate);
           
} catch (ParseException e) {
               
e.printStackTrace();
           
}
           
TextView dateText = (TextView) historyData.findViewById(R.id.mydate);
           
dateText.setText(DateFormat.format("MM/dd/yy",date));


//Change time format from military Hmmss to hh:mm:ss a

       
SimpleDateFormat df2 = new SimpleDateFormat("Hmmss");
           
Date date2 = null;
           
try {
               
date2 = df2.parse(inputTime);
           
} catch (ParseException e) {
               
e.printStackTrace();
           
}
           
TextView timeText = (TextView) historyData.findViewById(R.id.mytime);
           
timeText.setText(DateFormat.format("hh:mm:ss a",date2));

How to display required days ahead of current date in Android ListActivity?


Below is the Example.....................


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;


public class WeekDisplayActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListAdapter adapter = createAdapter();
        setListAdapter(adapter);
    }
    
    protected ListAdapter createAdapter()
    {
    SimpleDateFormat curFormater = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); 
         GregorianCalendar date = new GregorianCalendar();
         String[] dateStringArray = new String[7];


         for (int day = 0; day < 7; day++) {
             dateStringArray[day] = curFormater.format(date.getTime());
             date.roll(Calendar.DAY_OF_YEAR, true);
         }
   
    // Create a simple array adapter (of type string) with the test values
    ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dateStringArray);

    return adapter;
    }
}




Below is the Screenshot of Output..........



Monday, February 20, 2012

How to Add events to the calendar in Android 4.0 API ?


The latest version of the Android SDK, code-named Ice Cream Sandwich, reached developers this week. For the first time, the SDK provides access to the Calendar application in a legitimate fashion. One of the most common tasks that developers often want to be able to do is create new events in the user’s calendar, so today we’ll show you how.

The Calendar is a common application that users rely upon on their Android devices. Applications can access the Calendar using the new APIs available in Android 4.0. Adding new events to the Calendar is simple and requires no special application permissions.

Note: The user is responsible for configuring the Calendar application with the appropriate Calendar accounts (e.g. Microsoft Exchange).

Step 1: Getting Started

This tutorial assumes you have a project that supports Android 4.0 (API Level 14 compatible) and that you are compiling with the latest tools. It also assumes that you’ve properly configured the Calendar application on the Android emulator (or a suitable device, when one becomes available in the coming weeks).

Step 2: Create the Calendar Intent

In order to prompt the user to create a calendar event in their existing calendar, you’ll need to create the appropriate intent. This intent will launch the Calendar application with a screen that allows them to create a new event. The user must confirm this event and can add or change any of the event data associated with the event.

The intent to create a calendar event is shown below:
Intent calIntent = new Intent(Intent.ACTION_INSERT);
calIntent.setType("vnd.android.cursor.item/event");
startActivity(calIntent);

This code simply launches the intent. It does not set any of the calendar data associated with the event.

Step 2: Seeding Calendar Details


You can seed the information associated with a calendar event by supplying a number of intent extras. Extras can be used to describe event details, the date and time of the event, as well as calendar event settings like whether the event can be seen by others and whether it is busy or available time. The typical calendar event settings are all available as Extras. For example, the following intent call supplies some title and description information about an event:

Intent calIntent = new Intent(Intent.ACTION_INSERT);
calIntent.setType("vnd.android.cursor.item/event");
calIntent.putExtra(Events.TITLE, "My House Party");
calIntent.putExtra(Events.EVENT_LOCATION, "My Beach House");
calIntent.putExtra(Events.DESCRIPTION, "A Pig Roast on the Beach");
startActivity(calIntent);

Here we set the title, location, and description access for the event using the appropriate intent Extras. These fields will be set in a form that displays for the user to confirm the event in their calendar.

Step 3: Seeding Calendar Dates and Times


Calendar events are associated with specific dates and times. Some events have a specific time window and others are “all day” events. You can specify the date and time of an event using extras as well.
Effective with Ice Cream Sandwich (Android 4, API level 14), the new CalendarContract class holds, in a variety of nested classes, all the constants needed to make a portable calendar application. This is shown inserting a Calendar Event directly into the user's first Calendar (using id 1); obviously there should be a drop-down listing the user's calendars in a real application.

Intent calIntent = new Intent(Intent.ACTION_INSERT);
calIntent.setType("vnd.android.cursor.item/event");
calIntent.putExtra(Events.TITLE, "My House Party");
calIntent.putExtra(Events.EVENT_LOCATION, "My Beach House");
calIntent.putExtra(Events.DESCRIPTION, "A Pig Roast on the Beach"); 
 
GregorianCalendar calDate = new GregorianCalendar(2012, 7, 15);
calIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,calDate.getTimeInMillis());
calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,calDate.getTimeInMillis()); 
 
startActivity(calIntent);

Here we set the event to be an all day event on a specific date. You can also set much more fine-grained events by simply using the two extras for the beginning and ending time.

Step 4: Event Configuration Details


There are several other intent extras you can seed as well. These include whether or not others can see the event (access level) and whether or not the time should be shown as busy or available (availability)

You could set these extras as follows:
calIntent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE);
calIntent.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);

Step 5: Configuring Recurring Events

There are one-time events, like our pig roast, and then there are recurring events, like by-weekly meetings. You can seed the recurrence rule using an intent extra, like this:
calIntent.putExtra(Events.RRULE, “FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH”);
The RULE intent extra takes a standard iCalendar recurrence rule format (see RFC 5544 for details). For example, the one above creates a recurrence rule for an event that occurs every Tuesday and Thursday for 5 weeks.