I'm trying to make an app that tells me whats the next meeting in my calendar.
What I did is place a cursor on the last event and start getting their start times until I get to the one that's smaller than right now, then, simply use the previous item.
It works fine when creating events in order but not if I create an event in between.
Here is an example:
Lets set the time to 13:00 hours
I have events that I added before at 15:00 (event 1), 16:00 (event 2), 17:00 (event 3)
The cursor goes to read the start time of event 3.
Since the start time is bigger than right now, it goes to previous one, event 2
since start time is also bigger, it goes to previous one, event 1.
Since start time is also bigger, it goes to previous one, some event yesterday.
Since start is smaller, it gets the id, title and start and end times from event 1.
That all works fine, the problem is, when I add something at lets say 14:00 (event 0) after initially added the others first, events 1, 2 and 3
It wont get to event 0, it keeps the information of event 1.
How can I make so that it is correctly made?
here is my code
Big thanks in advance
Regards
public class CalendarInfo extends Activity {
int idNumber = 0;
private Cursor mCursor = null;
private static final String[] COLS = new String[]
{ CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events._ID};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_info);
Button buttonchange999 = (Button) findViewById(R.id.button999);
buttonchange999.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCursor = getContentResolver().query(
CalendarContract.Events.CONTENT_URI, COLS, null, null, null);
mCursor.moveToLast();
Calendar cal = Calendar.getInstance();
long currentTimeStart = cal.getTimeInMillis();
long ammountOfDayPassed = currentTimeStart/86400000;
String title = "N/A";
Long start = 9223372036854775806L;
Long end = 0L;
int id = 0;
String title2 = "N/A";
Long start2 = 9223372036854775806L;
Long end2 = 0L;
int id2 = 0;
while(start>currentTimeStart){
try {
title = mCursor.getString(0);
start = mCursor.getLong(1);
end = mCursor.getLong(2);
id = mCursor.getInt(3);
} catch (Exception e) {
//ignore
}
if(start>currentTimeStart){
title2 = title;
start2 = start;
end2 = end;
id2 = id;
}
mCursor.moveToPrevious();
}
DateFormat formatter01 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Calendar calendar01 = Calendar.getInstance();
calendar01.setTimeInMillis(start2);
String startText = formatter01.format(calendar01.getTime());
DateFormat formatter02 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Calendar calendar02 = Calendar.getInstance();
calendar02.setTimeInMillis(end2);
String endText = formatter02.format(calendar02.getTime());
if(start2>currentTimeStart && end2>currentTimeStart){
settingsTextView.setText("Meeting: "+title2+"\n"+"At: "+startText+"\n"+"Until: "+endText+"\n"+"ID: "+id2);
idNumber=id2;
}
else{
settingsTextView.setText("No Next Meeting" + "\n" + "Meeting: "+title2+"\n"+"At: "+startText+"\n"+"Until: "+endText+"\n"+"ID: "+id2);
idNumber=id2;
}
}
});
}
Solved adding one if in this line:
if(start>currentTimeStart){
if(start<start2){
title2 = title;
start2 = start;
end2 = end;
id2 = id;
}
}
Related
I have a table that store two variables Days and percent’s. I want to assign them to a specific variable. From the Database Helper class, I’m getting the last 7 entries:
//----------------Graping the last seven elements ----------------------------------//
public ArrayList<StatsitcsHelper> GetWeaklyPrograss() {
SQLiteDatabase db = this.getReadableDatabase ();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
ArrayList<StatsitcsHelper> datas = new ArrayList<>();
if (cursor != null) {
cursor.moveToFirst ();
for (int i = cursor.getCount () - 7 ; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
StatsitcsHelper data = new StatsitcsHelper();
data.WeakleyDate= cursor.getString(cursor.getColumnIndex(COL_P_Date));
data.WeakleyPercent = cursor.getInt (cursor.getColumnIndex(COL_P_Percentage));
datas.add(data);
cursor.moveToNext ();
}
cursor.close ();
}
return datas;
}
I want to build if statement that will say if day is Saturday then assign Saturday Percent Variable is Statistics Class to the percent associated from the database. Same goes for Sunday ….etc.
Inside the Statistics Class:
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity ());
//---------------------TO DO----------------------------------------//
}}
I don’t know how to analysis each item from the list in the database to another class.
Here is the Insertion of the Table:
// ----------------Proggres Table ------------------------------------//
public boolean insertPrograss(String Date, Integer percentage) {
SQLiteDatabase db = this.getWritableDatabase ();
ContentValues contentValues = new ContentValues ();
contentValues.put (COL_P_Date, Date);
contentValues.put (COL_P_Percentage, percentage);
long result = db.insert (TABLE_PROGGRES, null, contentValues);
db.close ();
return result != -1;
}
the method is called by scheduler that will store the date into just day by using date formate, and the output will be Monday, 87.
i want to write a method to get the last 7 inputs through GetWeaklyPrograss method. and assign it to the variables something like this
if(statsitcsHelper.WeakleyDate.equals ("monday")){
saturday = statsitcsHelper.WeakleyPercent;
}
and here is the statsitcsHelper:
public class StatsitcsHelper {
//-------------- Weakly Progress -----------------------/
public String WeakleyDate;
public int WeakleyPercent;
}
can you try this logic ,
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
//StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity());
ArrayList<StatsitcsHelper> statsitcsHelperList = databaseHelper.GetWeaklyPrograss();
for (StatsitcsHelper statsitcsHelper : statsitcsHelperList)
{
if(statsitcsHelper.WeakleyDate.equals("Monday")){
monday = statsitcsHelper.WeakleyPercent;
}else if (statsitcsHelper.WeakleyDate.equals("Tuesday")){
tuesday = statsitcsHelper.WeakleyPercent;
}
//todo and write for other days too
}
// In here you can use all valid data
}
I am not sure I understand what the problem is.
However to check the day of week, you can get some ideas from this:
check if date() is monday? java
On a side note:
Your cursor contains all of the data in the table! It is usually better to get the results you want (last seven elements) on your cursor.
Limit your DB query, down to the interesting data. Instead of taking all data from the DB (select * from), you should specialize your query.
Look for SQL expressions ORDER BY, ASC, DESC, LIMIT, and you will get there.
I have an empty list. I fill it with my class's instances in a loop. And right after adding an instance, I retrieve the last element and check its parameters. The values of parameters are fine.
Now, when I have filled all the values and control gets out of the loop, the date and time (which are instances of Calendar) of all the elements of that list are somehow replaced with the very last element's date and time, whereas the rest of parameters remain the same. I don't know if there is a logical error in my code or there is a bug in Android Studio.
I am printing out the values to Logcat, before entering the element and after entering that element. The values are same. But when the control reaches cursor.close(), all elements in that list are replaced.
public List<YearChart> readYearChart() throws Exception {
List<YearChart> yearChart = null;
SimpleDateFormat dateFormat = TheApplication.getDateFormat();
SimpleDateFormat timeFormat = TheApplication.getTimeFormat();
Cursor cursor = sqLiteDatabase.query(MyDatabaseHelper.table_YearChart, super.columnsToRetrieve, null, null, null, null, null);
if(cursor.moveToFirst()) {
yearChart = new ArrayList();
int id;
Calendar date = Calendar.getInstance();
int namazId;
Calendar time = Calendar.getInstance();
int i=0;
do
{
id = cursor.getInt(cursor.getColumnIndex(super.columnsToRetrieve[0]));
String dateStr = cursor.getString(cursor.getColumnIndex(super.columnsToRetrieve[1]));
namazId = cursor.getInt(cursor.getColumnIndex(super.columnsToRetrieve[2]));
String timeStr = cursor.getString(cursor.getColumnIndex(super.columnsToRetrieve[3]));
if(!dateStr.isEmpty() && !timeStr.isEmpty())
{
date.setTime(dateFormat.parse(dateStr));
time.setTime(timeFormat.parse(timeStr));
YearChart yc = new YearChart(id, date, namazId, time);
Log.v("YearChart_ID >", String.valueOf(yc.getId()));
Log.v("YearChart_Date>", TheApplication.getDateFormat().format(yc.getDate().getTime()));
Log.v("YearChart_NID >", String.valueOf(yc.getNamazId()));
Log.v("YearChart_Time>", TheApplication.getTimeFormat().format(yc.getTime().getTime()));
Log.v("*****", "*****");
yearChart.add(yc);
YearChart yc1 = yearChart.get(i);
Log.v("YearChart_ID >", String.valueOf(yc1.getId()));
Log.v("YearChart_Date>", TheApplication.getDateFormat().format(yc1.getDate().getTime()));
Log.v("YearChart_NID >", String.valueOf(yc1.getNamazId()));
Log.v("YearChart_Time>", TheApplication.getTimeFormat().format(yc1.getTime().getTime()));
Log.v("*****", "*****");
i++;
}
} while (cursor.moveToNext());
}
cursor.close();
return yearChart;
}
I am using Android Studio (v1.1.0).
You're passing the same reference to date and time - meaning each element in the list holds a reference to those exact objects. When you call date/time methods, you'll be updating those two variables which all your list items point to.
The solution is to move the instantiation of date and time into the do-while loop.
Okay, so I have a Android App that uses the built in NavigationDrawer Activity with Fragments for each view. One of the views pulls some data from a web service, but since the data doesn't change during a single day I store the values in the preferences as well as a timestamp for the day the tab was opened so that web service method isn't called every time the user opens that tab. The problem that I'm having though is that when the timestamp section just moves to the part of the code that updates the view some items aren't being drawn correctly (some are squished down while others aren't showing the correct placement on the screen). If I click the refresh button to call the web service methods and then update the view that way it always draws them correctly. I don't know where I'm messing up, but I'm sure it's me since Android is pretty new to me.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sales, container, false);
thisActivity = this.getActivity();
mtdHeaderTextView = (TextView)rootView.findViewById(R.id.mtdHeaderText);
mtdSeekBar = (SeekBar)rootView.findViewById(R.id.mtdSeekBar);
mtdTopSeekBar = (SeekBar)rootView.findViewById(R.id.mtdTopSeekBar);
mtdValueTextView = (TextView)rootView.findViewById(R.id.mtdValueTextView);
mtdGoalTextView = (TextView)rootView.findViewById(R.id.mtdGoalTextView);
mtdDateTextView = (TextView)rootView.findViewById(R.id.mtdDateTextView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
CheckTimeStamp();
}
public static void CheckTimeStamp() {
SharedPreferences preferences = HelperClass.PreferenceFileName(thisActivity);
String timeStamp = preferences.getString(Constants.keySalesTimeStamp, "");
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String currentTime = HelperClass.GetSimpleDateFormat(date);
if (currentTime.equals(timeStamp)) {
foundMTDValue = preferences.getString(Constants.keyMTDValue, "");
foundYTDValue = preferences.getString(Constants.keyYTDValue, "");
UpdateMTDProgress();-->this is the method that adds values to the textviews and seekbars
}
else {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constants.keySalesTimeStamp, currentTime);
editor.apply();
GetMTDValue(); -->this calls the web service to get values and then calls UpdateMTDProgress like above
}
}
Below is the code from the UpdateMTDProgres section
public static void UpdateMTDProgress() {
//First update Header Text View
SharedPreferences preferences = HelperClass.PreferenceFileName(thisActivity);
int mtdGoal = preferences.getInt(Constants.keyMonthlyGoal, 0);
double percentage = Double.parseDouble(foundMTDValue) / mtdGoal;
NumberFormat format = NumberFormat.getPercentInstance();
String percentageString = format.format(percentage);
mtdHeaderTextView.setText("MTD Commissions (" + percentageString + ")");
//Get Current Date and Number of Days in Month
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
int totalDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//Get Daily Goal for Rep based on mtdGoal and number of days
int dailyGoal = mtdGoal/totalDays;
//Get current day goal
int currentDayGoal = dailyGoal * currentDay;
//Check if current mtd value against currentdaygoal
if (Double.parseDouble(foundMTDValue) >= currentDayGoal) {
mtdSeekBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.seekbar_green));
}
else {
mtdSeekBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.seekbar_red));
}
//update progress seekbar values
mtdSeekBar.setMax(mtdGoal);
mtdSeekBar.setProgress((int) Double.parseDouble(foundMTDValue));
//update indicator seekbar values
mtdTopSeekBar.setMax(totalDays);
mtdTopSeekBar.setProgress(currentDay);
//Update Current Value and Goal TextViews
String currentValueString = HelperClass.ConvertStringToCurrency(foundMTDValue);
mtdValueTextView.setText(currentValueString);
String goalValueString = HelperClass.ConvertStringToCurrency(String.valueOf(mtdGoal));
mtdGoalTextView.setText(goalValueString);
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd");
String shortDate = dateFormat.format(date);
mtdDateTextView.setText(shortDate);
I'm making a basic Dashclock extension that polls CalendarContract.Events for a list of all calendar events synced to the user's device, retrieve the one that's scheduled to happen the soonest, and post the time, title, location, and desctiption. Here's my code:
public class FullCalService extends DashClockExtension {
public static final String[] FIELDS = { Events._ID, Events.TITLE,
Events.ALL_DAY, Events.EVENT_LOCATION, Events.DTSTART,
Events.EVENT_TIMEZONE, Events.DESCRIPTION };
public FullCalService() {
}
#Override
protected void onUpdateData(int arg0) {
TimeZone tz = TimeZone.getDefault();
long currentTimeMillis = Calendar.getInstance().getTimeInMillis() - tz.getRawOffset();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
Cursor c;
if (prefs.getBoolean("allDayAllowed", false)) {
c = getContentResolver().query(
Events.CONTENT_URI,
FIELDS,
new StringBuilder().append("(").append(Events.DTSTART)
.append(" >= ?)").toString(),
new String[] { Long.toString(currentTimeMillis) },
Events.DTSTART, null);
} else {
c = getContentResolver().query(
Events.CONTENT_URI,
FIELDS,
new StringBuilder().append("((").append(Events.ALL_DAY)
.append("= ?) AND (").append(Events.DTSTART)
.append(" >= ?))").toString(),
new String[] { Integer.toString(0),
Long.toString(currentTimeMillis) }, Events.DTSTART,
null);
}
if (c.moveToFirst()) {
long eventTimeMillis = c.getLong(c.getColumnIndex(Events.DTSTART));
// if (tz.inDaylightTime(new Date(eventTimeMillis))) {
// eventTimeMillis += tz.getDSTSavings();
// }
//Log.d("DesCal service", "Value of hoursToReveal: "+prefs.getString("hoursToReveal", "1"));
if (eventTimeMillis < currentTimeMillis + 360000
* Integer.parseInt(prefs.getString("hoursToReveal", "1"))) {
String title = c.getString(c.getColumnIndex(Events.TITLE));
String loc = c.getString(c
.getColumnIndex(Events.EVENT_LOCATION));
String time = DateUtils.formatDateTime(this, eventTimeMillis,
DateUtils.FORMAT_SHOW_TIME);
String desc = c.getString(c.getColumnIndex(Events.DESCRIPTION));
StringBuilder expandedBody = new StringBuilder(time);
if (!loc.isEmpty()){
expandedBody.append(" - ").append(loc);
}
expandedBody.append("\n").append(desc);
String uri = new StringBuilder(
"content://com.android.calendar/events/").append(
c.getLong(c.getColumnIndex(Events._ID))).toString();
publishUpdate(new ExtensionData()
.visible(true)
.status(time)
.expandedTitle(title)
.expandedBody(expandedBody.toString())
.icon(R.drawable.ic_dash_cal)
.clickIntent(
new Intent(Intent.ACTION_VIEW, Uri.parse(uri))));
c.close();
} else {
publishUpdate(new ExtensionData().visible(false));
c.close();
}
} else {
publishUpdate(new ExtensionData().visible(false));
c.close();
}
}
}
Upon first install, it appeared to work just fine. However, after the event began, it would not grab any future events. Is there a reason why the extension will not refresh itself?
How are you triggering further updates? You need to manually specify when you'd like to have onUpdateData called, e.g. when there's a change to a content provider, or when the screen turns on, etc. Extensions by default refresh only every 30 minutes or so. See the source for the built in calendar extension for example code.
My issue is, I have to make one demo application in which I wants to read the events of the Google calendar, for that I have manually inserted the events like the title of event, the time of events and the details of the whole events. now I need to just read those events form that calendar.
For that I have tried to use the gcode(google code) API which provides the calendar API class. But still I cant read those events.
That code above is pretty awful (and it does not seem to work in ICS - definitely the column names are different)
The page here:
http://developer.android.com/guide/topics/providers/calendar-provider.html
provides a much better overview.
A (much) simpler code to retrieve calendars:
public class CalendarContentResolver {
public static final String[] FIELDS = {
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_COLOR,
CalendarContract.Calendars.VISIBLE
};
public static final Uri CALENDAR_URI = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver;
Set<String> calendars = new HashSet<String>();
public CalendarContentResolver(Context ctx) {
contentResolver = ctx.getContentResolver();
}
public Set<String> getCalendars() {
// Fetch a list of all calendars sync'd with the device and their display names
Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, null, null, null);
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String displayName = cursor.getString(1);
// This is actually a better pattern:
String color = cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR));
Boolean selected = !cursor.getString(3).equals("0");
calendars.add(displayName);
}
}
} catch (AssertionError ex) { /*TODO: log exception and bail*/ }
return calendars;
}
}
Hope this helps!
Ok i found the answer of this whole of the concept that how to use the google calendar application integration with the android phone.
code:--
first you set this line which will goes to read the calendar events form the other class form your class which is current is the ApplicationSettings.java .
ReadCalendar.readCalendar(ApplicationSettings.this);
package com.mycalendarevents.android;
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;
public class ReadCalendar
{
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected"}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count="+cursor.getCount());
if(cursor.getCount() > 0)
{
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
System.out.println("eventCursor count="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
System.out.println("Title:"+title);
System.out.println("Begin:"+begin);
System.out.println("End:"+end);
System.out.println("All Day:"+allDay);
/* the calendar control metting-begin events Respose sub-string (starts....hare) */
Pattern p = Pattern.compile(" ");
String[] items = p.split(begin.toString());
String scalendar_metting_beginday,scalendar_metting_beginmonth,scalendar_metting_beginyear,scalendar_metting_begindate,scalendar_metting_begintime,scalendar_metting_begingmt;
scalendar_metting_beginday = items[0];
scalendar_metting_beginmonth = items[1];
scalendar_metting_begindate = items[2];
scalendar_metting_begintime = items[3];
scalendar_metting_begingmt = items[4];
scalendar_metting_beginyear = items[5];
String calendar_metting_beginday = scalendar_metting_beginday;
String calendar_metting_beginmonth = scalendar_metting_beginmonth.toString().trim();
int calendar_metting_begindate = Integer.parseInt(scalendar_metting_begindate.trim());
String calendar_metting_begintime = scalendar_metting_begintime.toString().trim();
String calendar_metting_begingmt = scalendar_metting_begingmt;
int calendar_metting_beginyear = Integer.parseInt(scalendar_metting_beginyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_beginday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_beginmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_begindate);
System.out.println("calendar_metting_begintime="+calendar_metting_begintime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_begingmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_beginyear);
/* the calendar control metting-begin events Respose sub-string (starts....ends) */
/* the calendar control metting-end events Respose sub-string (starts....hare) */
Pattern p1 = Pattern.compile(" ");
String[] enditems = p.split(end.toString());
String scalendar_metting_endday,scalendar_metting_endmonth,scalendar_metting_endyear,scalendar_metting_enddate,scalendar_metting_endtime,scalendar_metting_endgmt;
scalendar_metting_endday = enditems[0];
scalendar_metting_endmonth = enditems[1];
scalendar_metting_enddate = enditems[2];
scalendar_metting_endtime = enditems[3];
scalendar_metting_endgmt = enditems[4];
scalendar_metting_endyear = enditems[5];
String calendar_metting_endday = scalendar_metting_endday;
String calendar_metting_endmonth = scalendar_metting_endmonth.toString().trim();
int calendar_metting_enddate = Integer.parseInt(scalendar_metting_enddate.trim());
String calendar_metting_endtime = scalendar_metting_endtime.toString().trim();
String calendar_metting_endgmt = scalendar_metting_endgmt;
int calendar_metting_endyear = Integer.parseInt(scalendar_metting_endyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_endday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_endmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_enddate);
System.out.println("calendar_metting_begintime="+calendar_metting_endtime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_endgmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_endyear);
/* the calendar control metting-end events Respose sub-string (starts....ends) */
System.out.println("only date begin of events="+begin.getDate());
System.out.println("only begin time of events="+begin.getHours() + ":" +begin.getMinutes() + ":" +begin.getSeconds());
System.out.println("only date begin of events="+end.getDate());
System.out.println("only begin time of events="+end.getHours() + ":" +end.getMinutes() + ":" +end.getSeconds());
beg_date = begin.getDate();
mbeg_date = begin.getDate()+"/"+calendar_metting_beginmonth+"/"+calendar_metting_beginyear;
beg_time = begin.getHours();
System.out.println("the vaule of mbeg_date="+mbeg_date.toString().trim());
end_date = end.getDate();
end_time = end.getHours();
CallHandlerUI.metting_begin_date.add(beg_date.toString());
CallHandlerUI.metting_begin_mdate.add(mbeg_date.toString());
CallHandlerUI.metting_begin_mtime.add(calendar_metting_begintime.toString());
CallHandlerUI.metting_end_date.add(end_date.toString());
CallHandlerUI.metting_end_time.add(end_time.toString());
CallHandlerUI.metting_end_mtime.add(calendar_metting_endtime.toString());
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}
here is the whole of the code is to be posted which will simply reads each and every events form your calendar with the help of that postback url which is for 2.2 and above version:
Uri.parse("content://com.android.calendar/instances/when").buildUpon();
pl find the under those version lower then 2.2 in android and use those events as you required place...
I am aware that this is an old post, but I found inspiration for optimizing the solution found in the answer given by Akash Takkar if anyone is in need of a solution in the near future.
The issues
Specically, I found a few issues in the original code:
The loop for retrieving calendar events broke immaturely
Hereby, only events from the first calendar was retrieved
The first event in each calendar was skipped by using eventCursor.moveToFirst(); which thereafter moves directly to the next event in the while loop
The id of the calendars were not set correctly in the eventCursor
"Calendars._id=" + 1, should be "Calendars._id=" + id,
It would be difficult for others to specify their own time range
The current solution is not object oriented which would hold many advantages
The readability and documentation is not the best
The solution
I have hereby created a Github Library which returns a list of event objects in a specified time range which can be found at:
https://github.com/david-laundav/CalendarService
The source files can be found under "CalendarService/src/dk/CalendarService".
Use cases
The solution itself contains two different methods for different purposes.
First use case:
CalendarService.readCalendar(class.this)
// where class.this is either your class or the context
This method will return a list of events for +/- 1 day
Second use case:
You can also specify your own time range:
CalendarService.readCalendar(class.this, int days, int hours)
An example might be:
CalendarService.readCalendar(class.this, 2, 5)
In doing so will return a list of events from +/-2 days and +/- 5 hours.
The service has been tested, but please tell me if you experience any issues.
This post is a little bit old, but here is another easy solution for getting data related to Calendar content provider in Android:
Use this lib: https://github.com/EverythingMe/easy-content-providers
And now, get all calendars:
CalendarProvider calendarProvider = new CalendarProvider(context);
List<Calendar> calendars = calendarProvider.getCalendars().getList();
Each Calendar has all fields, so you can get any info you need:
id, name, calendarColor, ownerAccount, accountName, calendarAccessLevel, ...
Or, get all Events of specific calendar:
List<Event> calendars = calendarProvider.getEvents(calendar.id).getList();
And there is also option to get Reminders, Attendees, Instances.
It works with lists or cursor and there a sample app to see how it looks and works.
In fact, there is support for all Android content providers like: Contacts, SMS, Calls, ...
Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers
Hope it helped :)
Use this code get the calendar events for one day.
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("MMMM dd, yyyy (EEEE)");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("23:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
/*String[] COLS={"calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation"};
cursor = contentResolver.query(
CalendarContract.Events.CONTENT_URI, COLS,null, null, null);*/
gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
dt=convertDate(dtstart1,"hh:mm:ss");
googleCalendar.setDtstart(dt);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventTimeZone=cursor.getString(5);
googleCalendar.setEventTimeZone(eventTimeZone);
String eventlocation = cursor.getString(6);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}