How to get events from google accounts calendar in android? - java

I am using this code and getting the events from the calendar and it is working fine but, I want to get the events from google accounts calendar .For example, I want to get the (deepakcando90#gmail.com )google calendar accounts events also? I know it is possible but do not know how to implement it?
my code is ,
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("EEEE, MMMM dd, yyyy");
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("47:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
gCalendar = new ArrayList<GoogleCalendar>();
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()) {
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);
googleCalendar.setDtstart(dtstart1);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

How to get all events from SQlite database in Alamkanak Android-Week-View library ? (i keep getting single Event)?

I am trying to add events dynamically from the my SQLite database , but i get a single event in my Week-view which it is the last event i add in the database , i am using Alamkanak Week-View , i stuck with problem and try many ways , please help guys .
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
ArrayList<WeekViewEvent> lastevents = new ArrayList<WeekViewEvent>();
lastevents = loadDateFromJson(newYear,newMonth);
events.addAll(loadDateFromJson(newYear,newMonth));
return events;
}
} );
}
public ArrayList<WeekViewEvent> getmNewEvents(int year , int month ) {
// Parse time.
SimpleDateFormat sdf = new SimpleDateFormat("HH:MM");
Date start = new Date();
Date end = new Date();
start = getMyTime();
try {
end = sdf.parse(new Event().getEndTime());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
Calendar startTime = (Calendar) now.clone();
startTime.setTimeInMillis(start.getTime());
startTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
startTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
startTime.set(Calendar.DAY_OF_MONTH, getMyDate());
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, 3);
// Create an week view event.
ArrayList<WeekViewEvent> ThisMonthsEvents = new ArrayList<WeekViewEvent>();
WeekViewEvent weekViewEvent =new WeekViewEvent(1,"Raouf",startTime,endTime);
mNewEvents.add(weekViewEvent);
for (int i = 0; i < mNewEvents.size(); i++) {
mNewEvents.get(i).getStartTime().get(Calendar.MONTH);
if((mNewEvents.get(i).getStartTime().get(Calendar.MONTH) == month)&&(mNewEvents.get(i).getStartTime().get(Calendar.YEAR) == year))
ThisMonthsEvents.add(mNewEvents.get(i));
}
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : mNewEvents) {
if (eventMatches(event, year, month)) {
matchedEvents.add(event);
}
}
mWeekView.notifyDatasetChanged();
return ThisMonthsEvents;
}
// here how i am getting dates from my SQlite Database
public int getMyDate() {
DBconexion db = new DBconexion(this);
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cur = db2.rawQuery("SELECT * FROM " + Table_name, null);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy");
// looping through all rows and adding to list
String date = null;
Date Date = new Date();
ArrayList<String> dateStringList = new ArrayList<String>();
ArrayList<Date> dateList = new ArrayList<Date>();
int DayOfMonth = 0;
while (cur.moveToNext()) {
dateStringList.add(cur.getString(9));
}
for (String dateString : dateStringList) {
try {
dateList.add(simpleDateFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
}
for (Date datee : dateList) {
DayOfMonth = datee.getDate();
}
return DayOfMonth;
}
i find how to solve this , i use JSONArrays and it works perfectly
here is the code maybe someone will need it!
public List<WeekViewEvent> loadDateFromJson(int year , int month) {
DBconexion dBconexion = new DBconexion(this);
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfD = new SimpleDateFormat("yy-MM-dd");
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfT = new SimpleDateFormat("HH:mm");
try {
JSONObject jo = dBconexion.getDateTime();
JSONArray Datejason = jo.getJSONArray("Date");
JSONArray Timejason = jo.getJSONArray("Time");
JSONArray endTimejason = jo.getJSONArray("End Time");
JSONArray Namejason = jo.getJSONArray("Name");
for (int i = 0; i < Datejason.length(); i++) {
//set date
String sd = (String) Datejason.get(i);
Date dfj = sdfD.parse(sd);
int Day = dfj.getDate();
int Month = dfj.getMonth() - 0;
int Year = dfj.getYear();
//set time
String st = (String) Timejason.get(i);
Date tfj = sdfT.parse(st);
int Hour = tfj.getHours();
int Minute = tfj.getMinutes();
String endTimeP = (String) endTimejason.getString(i);
int endTimePeriod = Integer.valueOf(endTimeP);
//set name
String Name = (String) Namejason.getString(i);
//Rand Colors for Events
Random rand = new Random();
int r = rand.nextInt(255);
int g = rand.nextInt(255);
int b = rand.nextInt(255);
int randomColor = Color.rgb(r,g,b);
if(Color.rgb(r,g,b) == getResources().getColor(R.color.white)){
randomColor = getResources().getColor(R.color.red);
}
//Set StarTime
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, Hour);
startTime.set(Calendar.MINUTE, Minute);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, Month);
startTime.set(Calendar.DAY_OF_MONTH, Day);
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, endTimePeriod);
WeekViewEvent weekViewEvent = new WeekViewEvent(1, Name, startTime, endTime);
weekViewEvent.setColor(randomColor);
myEvent.add(weekViewEvent);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return myEvent;
}
onMonthChange will look like
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
List<WeekViewEvent> lastone = new ArrayList<WeekViewEvent> ();
lastone = loadDateFromJson( newYear , newMonth);
events.addAll(lastone);
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : events) {
if (eventMatches(event, newYear, newMonth)) {
matchedEvents.add(event);
}
}
return matchedEvents;
}
} );
}

Parameter index out of range (3 > number of parameters, which is 2) error

I get the following error when I try to talk to my SQL database.This method gets two string values from a JSP page. The code gets this weeks dates set by the first int.
However, the problem is when I'm trying to talk to the database. It must be a syntax error. I've tried using different brackets
public String getSpecificSpot(String day, String hour) {
String result = "";
int dayNo= Integer.parseInt(day);
Calendar cal = GregorianCalendar.getInstance();
//System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String monday = "";
monday = df.format(cal.getTime());
//System.out.println(monday);
cal.add(Calendar.DATE, dayNo);
String currentDay = df.format(cal.getTime());
String currentDay2= currentDay;
System.out.println("Current DAY: "+currentDay);
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from timetableslot WHERE date BETWEEN ? 00:00:00.00' AND ? 23:59:59.999' and time= ? ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, currentDay);
inserter.setString(2, currentDay2);
inserter.setString(3, hour);
System.out.println("validating user: " + query);
ResultSet resultSet = inserter.executeQuery();
while (resultSet.next()) {
//result = resultSet.getInt("classID");
result= String.valueOf(resultSet.getInt("slotID"));
System.out.println(result+" result value");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
//result="ssa";
return result;
}
The error that I get is:
java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).
Hi I have fixed it just after posting the question
public String getSpecificSpot(String day, String hour) {
String result = "";
int dayNo= Integer.parseInt(day);
Calendar cal = GregorianCalendar.getInstance();
//System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String monday = "";
monday = df.format(cal.getTime());
//System.out.println(monday);
cal.add(Calendar.DATE, dayNo);
String currentDay = df.format(cal.getTime());
String currentDay2= currentDay;
System.out.println("Current DAY: "+currentDay);
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from timetableslot WHERE date BETWEEN ? AND ? and time= ? ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, currentDay + " 00:00:00.00");
inserter.setString(2, currentDay2+ " 23:59:59.999");
inserter.setString(3, hour);
System.out.println("validating user: " + query);
ResultSet resultSet = inserter.executeQuery();
while (resultSet.next()) {
//result = resultSet.getInt("classID");
result= String.valueOf(resultSet.getInt("slotID"));
System.out.println(result+" result value");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
//result="ssa";
return result;
}

How to Disable date ranges in java calendar

In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.

how to remove data from hashtable for a particular date

I am trying to remove data from hashtable for a particular date,the hashtable is of type (String,vector).Initially i am checking if hashtable contains the usrDate if yes then i need to remove all the data frm hashtable only for usrDate and add the new data that is listEvents.But the contains from hashtable for other dates should not be deleted.
listEvents.addElement(eventBean);//new data is here
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
}
//checking if hashtable has given date
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector)listUserEvents.get(usrDate);
info.addElement(eventBean);
listUserEvents.put(usrDate,info);
} else {
listUserEvents.put(usrDate,listEvents);
}
i just want to add listEvents to the hashtable for the given date,without affecting the other data in hashtable which has data for some other dates.
private Hashtable getEvents(String usrDate, String timezone) {
try {
listUserEvents = getUserInfo();
listEvents = new Vector();
Calendar calendarLocalEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEvent = calendarLocalEvent.getTimeZone();
System.out.println("Time Zone first-->"
+ timeZoneEvent.getDefault());
if (timezone.equals(timeZoneEvent.getDefault())) {
;
} else {
TimeZone timeZoneChange = TimeZone.getTimeZone(timezone);
System.out.println("Time Zone change-->" +timeZoneChange);
Device.setTimeZone(timeZoneChange);
}
EventList eventList = (EventList) PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START)
&& event.countValues(Event.START) > 0)
{
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd,yyyy HH:mm");
SimpleDateFormat sdf_start = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdf_start_min = new SimpleDateFormat("HH");
String dateString = sdf.formatLocal(start);
String timeString = sdf_start.formatLocal(start);
String hour = sdf_start_min.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" + date +"user" + usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventData eventBean = new EventData();
if (eventList.isSupportedField(Event.END)
&& event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat(
"MMM dd, yyyy HH:mm");
SimpleDateFormat sdfTime = new SimpleDateFormat(
"HH:mm");
SimpleDateFormat sdfhr = new SimpleDateFormat("HH");
String dateString1 =sdform.formatLocal(end);
String timeString1 =sdfTime.formatLocal(end);
String hr = sdfhr.formatLocal(end);
eventBean.setStartHr(hour);
eventBean.setEndHr(hr);
eventBean.setStartTime(timeString);
eventBean.setEndTime(timeString1);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
// Dialog.alert("equal startdate" + dateString);
// Dialog.alert("equal end date"+ dateString1);
}
if (eventList.isSupportedField(Event.LOCATION)
&& event.countValues(Event.LOCATION) > 0) {
String location = event
.getString(Event.LOCATION, 0);
eventBean.setLocation(location);
// Dialog.alert("equal location"+ location);
}
if (eventList.isSupportedField(Event.SUMMARY)
&& event.countValues(Event.SUMMARY) > 0) {
String subject = event.getString(Event.SUMMARY, 0);
eventBean.setSummary(subject);
// Dialog.alert("equal subject" +subject);
}
eventBean.setUserDate(usrDate);
eventBean.setTimeZone(timezone);
listEvents.addElement(eventBean);
System.out.println("the size bf hashis"
+ listEvents.size());
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
System.out.println("so thesummary is ::"
+ e.getSummary());
}
// for(int i=0;i<listUserEvents.size();i++){
if (listUserEvents.containsKey(usrDate)) {
// listUserEvents.remove(usrDate);
Vector info = (Vector)listUserEvents.get(usrDate);
System.out.println("the size in getEvents is"
+ info.size());
if(info.contains(usrDate)){
System.out.println("in info");
}
info.addElement(eventBean);
System.out.println("vector size info is"
+ info.size());
listUserEvents.put(usrDate,info);
} else {
System.out.println("in else of getevent" +listEvents.size());
listUserEvents.put(usrDate,listEvents);
}
// }
} else {
// Dialog.alert("not equal");
}
}
}
Device.setTimeZone(timeZoneEvent);
Calendar calendarLocalLastEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEventLast =calendarLocalLastEvent.getTimeZone();
System.out.println("Time Zone last-->"
+ timeZoneEventLast.getDefault());
} catch (PIMException e) {
// //Dialog.alert(e.getMessage());
}
System.out.println("size in hashtable " + listUserEvents.size());
return listUserEvents;
}
It must be something like this
for(int i = 0; i<listUserEvents.size();i++)
{
if (listUserEvents.containsKey(usrDate)){
listUserEvents.remove(usrDate);
}
}
Here is a simple example of how this works:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
if (numbers.containsKey("two")) {
numbers.put("two", 222);
}
What are you having difficulty at? Moreover what is the type of your Hashtable key? Is it java.util.Date or something else?

Gettin date from a SMS message android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android - get date time from SMS timestamp in miliseconds
I am using the following code to record sms messages:
public void getColumnData(Cursor cur, Context context) {
ArrayList<String> exportBuffer = new ArrayList<String>();
try {
if (cur.moveToFirst()) {
String id;
String date;
String phoneNumber;
String body;
int idColumn = cur.getColumnIndex("_id");
int dateColumn = cur.getColumnIndex("date");
int numberColumn = cur.getColumnIndex("address");
int bodyColumn = cur.getColumnIndex("body");
do {
id = cur.getString(idColumn);
date = cur.getString(dateColumn);
body = cur.getString(bodyColumn);
phoneNumber = cur.getString(numberColumn);
String FormattedDate;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
FormattedDate = sdf.format(date).toString();
exportBuffer.add(id + " ," + FormattedDate + " ," + body + " ,"
+ phoneNumber);
} while (cur.moveToNext());
}
WriteToFile(exportBuffer,context);
} catch (Exception e) {
int MessageDuration = Toast.LENGTH_SHORT;
CharSequence text = "An Error Occurred, Code:104";
Toast toast = Toast.makeText(context, text, MessageDuration);
toast.show();
}
}
It all works fine apart from the date string I have no idea what format it is in which means I can't format it to a correct date here is an example of one of the dates:
1309817682651
Thanks in advance.
Try using this piece of code:
public static String millisToDate(long currentTime) {
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
finalDate = date.toString();
return finalDate;
}

Categories