Related
Here the user is able to pick a date(goal date) using datepicker. The date gets saved in the database. Then the notification pops up on the screen only if the due date is within 2 days. I wanted to figure out how to show the notification on a daily / weekly / monthly basis depending on the date selected. I checked different sites but didnt get a proper solution. Please help!
MainActivity
swipelist.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
// ApplicationInfo item = mAppList.get(position);
final MyImage image = (MyImage) swipelist.getItemAtPosition((int) position);
switch (index) {
case 0:
// open
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View DateView = li.inflate(R.layout.calendar_cam, null);
build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Reminder");
build.setMessage("Pick a date");
build.setView(DateView);
newDate = (Button) DateView.findViewById(R.id.buttonCalCam); //Button which opens the calender
newDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
currentYear = c.get(Calendar.YEAR);
currentMonth = c.get(Calendar.MONTH);
currentDay = c.get(Calendar.DAY_OF_MONTH);
build.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBhelper.COLUMN_DESCRIPTION, dateString);
Log.d("Updating Date: ", ".....");
String whereClause =
DBhelper.COLUMN_TITLE + "=? AND " + DBhelper.COLUMN_DATETIME + "=?";
String[] whereArgs = new String[]{image.getTitle(), String.valueOf(image.getDatetimeLong())};
database.update(DBhelper.TABLE_NAME, cv, whereClause, whereArgs);
Log.d("Updating Date: ", ".....");
image.setDescription(dateString);
swipelist.invalidateViews();
//Scheduling Notifications
int curYear = c.get(Calendar.YEAR), curMonth = c.get(Calendar.MONTH) + 1, curDay = c.get(Calendar.DAY_OF_MONTH);
int goalYear = Integer.parseInt(yearG), goalMonth = Integer.parseInt(monthG), goalDay = Integer.parseInt(dayG);
int calYear = 0, calMonth = 0, calDay = 0, calDayGoal = 0;
//Get current date
String curDate = String.valueOf(curDay) + "/" + String.valueOf(curMonth) + "/" + String.valueOf(curYear);
//Get goal date
String goalDate = String.valueOf(goalDay) + "/" + String.valueOf(goalMonth) + "/" + String.valueOf(goalYear);
int count = -1;
//Fetches the date and Time from system, hence not used
if (curYear < goalYear || (goalYear == curYear && goalMonth > curMonth) || (goalYear == curYear && goalMonth == curMonth && goalDay > curDay)) {
count = 0;
int i;
for (i = curYear; i < goalYear; i++) {
if (i % 4 == 0) {
count += 366;//Leap year
} else {
count += 365;// Non leap year
}
}
//calculating the no of days left from current date to goal date
count -= calMonthDay(curMonth, curYear);
count -= curDay;
count += calMonthDay(goalMonth, goalYear);
count += goalDay;
if (count < 0) {
count *= -1;
}
if (count != 1) {
daysLeftGoal.add(String.valueOf(count) + " days left");
Toast.makeText(getBaseContext(), "Days Left: "+count, Toast.LENGTH_LONG).show();
}else
daysLeftGoal.add(String.valueOf(count) + " day left");
} else {// current year exceeds goal year
daysLeftGoal.add("Times up");
}
mContext=getApplicationContext();
// check if goal date is less than or equals 2 days
if (count <= 2 && count >= 0) {
Intent resultIntent = new Intent(mContext, MainActivity.class);
//resultIntent.putExtra("ID", mCursor.getString(mCursor.getColumnIndex(DbHelperGoal.KEY_ID)));
resultIntent.putExtra("update", true);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//TaskStackBuilder requires API 16 [4.1] min
if (Build.VERSION.SDK_INT > 15) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
//stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
} else {
resultPendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//deletePendingIntent = PendingIntent.getActivity(MainActivity.this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
gBuilder = new NotificationCompat.Builder(MainActivity.this).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Goals")
.setContentText("Reminder Set: " + image.getDescription())
.addAction(R.drawable.ic_action_about, "View", resultPendingIntent);
//.addAction(R.drawable.ic_action_discard, "Delete", deletePendingIntent);
gBuilder.setContentIntent(resultPendingIntent);
//gBuilder.setContentIntent(deletePendingIntent);
gBuilder.setPriority(2);// [-2,2]->[PRIORITY_MIN,PRIORITY_MAX]
//for the sound and float notification
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 14);//set the alarm time
calendar.set(Calendar.MINUTE, 57);
calendar.set(Calendar.SECOND, 0);
gBuilder.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}).setLights(Color.WHITE, 0, 1);
//gBuilder.setWhen(calendar.getTimeInMillis()).setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }).setLights(Color.WHITE, 0, 1);
// opens the resultPendingIntent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// open the activity every 24 hours
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, resultPendingIntent);
gBuilder.setAutoCancel(true);
//int mNotificationId = mCursor.getInt(mCursor.getColumnIndex(DbHelperGoal.KEY_ID));
//keyIndex = mCursor.getInt(mCursor.getColumnIndex(DbHelperGoal.KEY_ID));
int mNotificationId=position;
// Gets an instance of the NotificationManager service
myGoalNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
myGoalNotifyMgr.notify(mNotificationId, gBuilder.build());
}
}
});
alert=build.create();
alert.show();
break;
// calculates days from months
int calMonthDay(int m,int y){//calMonthDay(month,year)
int x=0,c;
for(c = 1; c < m; c++) {// Jan to less than the month 'm' as 'm' we are not taking the the whole days of that month
if(c == 2) {//if Feb
if(y%4 == 0)//checks if year is leap or not
x += 29;
else
x += 28;
}
else
x += mon.get(c-1);
}
return(x);
}
//calculates no. of months from current month & year to goal month & year
int calDateMonth(int mC,int yC,int mG,int yG){//(current-month, current-year, goal-month, goal-year)
int x = 0,i,countM=0;
if(yC<=yG){
for(i = yC; i < yG; i++)
countM += 12;
}
countM -= mC;
countM += mG;
return (countM);
}
//calculates no. of weeks from current month & year to goal month & year
int calDateWeek(int mC,int yC,int mG,int yG){
int x = 0,i,countW=0;
if(yC<=yG){
for(i = yC; i < yG; i++)
countW+=52;
}
countW -= mC;
countW += mG;
countW *= 4;
return (countW);
}
DatePicker
private DatePickerDialog.OnDateSetListener reservationDate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day){
final Calendar c = Calendar.getInstance();
Date convertedDate = new Date();
int curYear = c.get(Calendar.YEAR), curMonth = c.get(Calendar.MONTH)+1, curDay = c.get(Calendar.DAY_OF_MONTH);
//Picks the selected date, month & year & displays on button
if((year>curYear)||(year==curYear && month+1>curMonth)||(year==curYear && month+1==curMonth && day>curDay)) {
dayG = Integer.toString(day);
monthG = Integer.toString(month + 1);
yearG = Integer.toString(year);
Log.d("Setting Date: ", ".....");
dateString=String.valueOf(dayG)+"-"+String.valueOf(monthG)+"-"+String.valueOf(yearG);
Toast.makeText(getBaseContext(), "Your reminder is set to " + day + "-" + (month + 1) + "-" + year + ".", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "Please choose date after " + curDay + "-" + curMonth + "-" + curYear, Toast.LENGTH_SHORT).show();
}
}
};
I have a problem with my TotalCalendar class. In this class I'm adding every events ( for example: 20 events ) to my own calendar. I should add this events to Google Calendar, but stil it's adding to device calendar. How can I change it? When I put single event to calendar, I can choose kind of calendar, but in this situation, I can't.
public class TotalCalendar {
Context mContext;
Intent mIntent;
public TotalCalendar(Context context) {
this.mContext = context;
}
public boolean insert(String dzien, String miesiac, String lokacja, String tytul, String opis, String godziny) {
int year = Calendar.getInstance().get(Calendar.YEAR);
Calendar beginTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
if((Miesiac(miesiac) == 0) && (currentMonth == 11) )
{
year++;
}
int hh1 = 0;
int mm1 = 0;
int hh2 = 0;
int mm2 = 0;
if(isNumeric(getHH1(godziny)) && isNumeric(getMM2(godziny)))
{
Log.d("debug","numeric");
hh1 = Integer.valueOf(getHH1(godziny)).intValue();
mm1 = Integer.valueOf(getMM1(godziny)).intValue();
hh2 = Integer.valueOf(getHH2(godziny)).intValue();
mm2 = Integer.valueOf(getMM2(godziny)).intValue();
}
else
{
hh1 = 0;
mm1 = 0;
hh2 = 0;
mm2 = 0;
}
beginTime.set(year, Miesiac(miesiac), Integer.valueOf(dzien).intValue(), hh1, mm1);
endTime.set(year, Miesiac(miesiac), Integer.valueOf(dzien).intValue(), hh2, mm2);
Log.d("debug", "Begin time: " + Miesiac(miesiac) + " " + Integer.valueOf(dzien));
long startMillis = beginTime.getTimeInMillis();
long endMillis = endTime.getTimeInMillis();
ContentResolver cr = mContext.getContentResolver();
ContentValues values = new ContentValues();
TimeZone tz = TimeZone.getDefault();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.TITLE,tytul);
values.put(CalendarContract.Events.DESCRIPTION,opis);
values.put(CalendarContract.Events.CALENDAR_ID,1);
values.put(CalendarContract.Events.EVENT_TIMEZONE,tz.getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI,values);
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
ContentUris.appendId(builder, startMillis);
this.mIntent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(mIntent);
return true;
}
I am using alam kanak week view in my app. I have an event for which I know the date, the start time and the end time. Now what function to call to add this event to the weekview. Suppose the date I have is 20-10-2015 and time is 17:30 to 18:30.
I am unable to add this event to the view. Please provide if there is anything.
This is how Alam-Kanak is adding an event:
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 5);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.MONTH, newMonth-1);
startTime.set(Calendar.YEAR, newYear);
startTime.add(Calendar.DATE, 1);
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, 3);
endTime.set(Calendar.MONTH, newMonth - 1);
WeekViewEvent event = new WeekViewEvent(3, "Test title", startTime, endTime);
event.setColor(getResources().getColor(R.color.event_color_03));
CommonItems.events.add(event);
This event shows up.
This is the response I am getting from my server for my custom event:
{ "error": false, "appointments": [
{
"id": "1",
"staff_id": null,
"technician_id": "1",
"name": "Test",
"address": "Vijayanagar",
"pincode": "580040",
"mobile": "9876543210",
"email": "test#gmail.com",
"date": "2015-09-22",
"time": "16:30:00",
"latitude": null,
"longitude": null,
"status": "open",
"created_at": "2015-09-06 18:04:47",
"updated_at": null
} ] }
This is how I am adding my event:
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("appointments");
for (int i = 0; i < ja.length(); i++) {
JSONObject index = ja.getJSONObject(i);
String name = index.getString("name");
String date = index.getString("date");
String[] dateSplit = date.split("-");
int date_year = Integer.parseInt(dateSplit[0]);
int date_month = Integer.parseInt(dateSplit[1]);
int date_day = Integer.parseInt(dateSplit[2]);
String time = index.getString("time");
String[] timeSplit = time.split(":");
int time_hour = Integer.parseInt(timeSplit[0]);
int time_minute = Integer.parseInt(timeSplit[1]);
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 4);
startTime.set(Calendar.MINUTE, time_minute);
startTime.set(Calendar.DATE, date_day);
startTime.set(Calendar.MONTH, date_month);
startTime.set(Calendar.YEAR, date_year);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, 4+1);
endTime.set(Calendar.MINUTE, time_minute);
WeekViewEvent event = new WeekViewEvent(1, name, startTime, endTime);
event.setColor(getResources().getColor(R.color.event_color_01));
CommonItems.events.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This wont show up.! I am unable to understand whats wrong. Please help.
I have done this way by little bit change in library:
Change onSingleTapConfirmed #Override method:
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mEventClickListener != null) {
boolean didSelect = false;
if (mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left
&& e.getX() < event.rectF.right
&& e.getY() > event.rectF.top
&& e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(
event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
didSelect = true;
break;
}
}
}
if (!didSelect) {
int day_1 = mFirstVisibleDay.get(Calendar.DAY_OF_YEAR);
int day_2 = mLastVisibleDay.get(Calendar.DAY_OF_YEAR);
int chosen_day;
if (day_1 != day_2) {
chosen_day = (int) (day_1 - 1 + Math.round((e.getX() - mHeaderColumnPadding - (mNumberOfVisibleDays-1)*mColumnGap - mTextSize)
/ mWidthPerDay));
} else {
chosen_day = day_1;
}
Calendar RETCAL = Calendar.getInstance();
RETCAL.setTime(mFirstVisibleDay.getTime());
// int totalY = mScroller
int chosen_hour = Math.max(Math.min((int) Math.round((e.getY() - mHeaderTextHeight - mHeaderRowPadding - mHeaderMarginBottom - mScroller
.getCurrY()) / mHourHeight),23),0);
RETCAL.set(Calendar.DAY_OF_YEAR, chosen_day);
RETCAL.set(Calendar.HOUR_OF_DAY, chosen_hour-1);
RETCAL.set(Calendar.MINUTE, 0);
mEventClickListener.onNonEventSingleTap(RETCAL);
}
}
return super.onSingleTapConfirmed(e);
}
EventClickListener interface will looks like below:
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
public void onNonEventSingleTap(Calendar cal);
}
Now you will get Calendar object in your Activity or Fragment class:
#Override
public void onNonEventSingleTap(Calendar cal) {
// User cal object as Calendar
}
Hope this will help you.
hi mate y have this code and it works for me.
there you got two ways to add events.
the thing is that when you add the month variable it needs to be (month-1)
like if you want to add an event on july you must insert 7-1=6;
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.DAY_OF_MONTH, 19);
startTime.set(Calendar.HOUR_OF_DAY, 1);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.MONTH, 10);
startTime.set(Calendar.YEAR, 2015);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.DAY_OF_MONTH, 19);
endTime.set(Calendar.HOUR_OF_DAY, 5);
endTime.set(Calendar.MINUTE, 0);
endTime.set(Calendar.MONTH, 10);
endTime.set(Calendar.YEAR, 2015);
WeekViewEvent event = new WeekViewEvent(0, "Epoca", startTime, endTime);
event.setColor(getResources().getColor(R.color.orange));
events.add(event);
startTime = Calendar.getInstance();
startTime.set(2015, 10, 19, 6, 00);
endTime = Calendar.getInstance();
endTime.set(2015, 10, 19, 9, 00);
WeekViewEvent event2 = new WeekViewEvent(0,"00kjbhjbhjbjbhj",startTime, endTime);
event2.setColor(getResources().getColor(R.color.orange));
events.add(event2);
return events;
}
hope it helps.
may be the issue is your events are added but u have set the event month as startTime.set(Calendar.MONTH, date_month); it is not the previous month. so your events are added on the same date of previous month. check that.. if thats the case then just replace that line with
startTime.set(Calendar.MONTH, date_month+1);
Okay, this is more of a speed issue. The problem is that I am fetching three fields from varied sources like Contacts, Facebook and Google plus. The three fields are a date, name and a contact image URi. The logic is such that each of the sources writes to a File, Contacts -- to file, Facebook - append to same file, Google Plus - append to same file. This operation is pretty fast and takes the normal time to execute. This creates my original Data source. Then from this file I fetch each record (Row with three fields) individually and do some calculations and write data pertaining to each record into three different database tables. While as this works pretty fast on a Quad Core phone, the process is too slow on a dual core phone. It takes around ten minutes to process 150 records on a dual core, takle four minutes to process 150 records on Quad core. I am perplexed as in how to increase the speed? Should I drop the idea of making a file as my original Data Source and instead switch to a Database table? What would be the fastest?
The code is as follows:
private class MagicCall extends AsyncTask<Void, String, String> {
int years;
long secon;
long min;
int hours;
int mon;
int days;
int weeks;
String CONTACT_ID,CONTACT_NAME,CONTACT_IMAGE_URI;
ProgressDialog Asycdialog = new ProgressDialog(LoaderClass.this);
#Override
protected void onPreExecute() {
boolean DIALOG_SHOW = true;
try{
BufferedReader br = null;
if(FLAG ==1){
br = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/xxxinders/fileone.txt"));
}else{
br = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/xxxinders/output.txt"));
}
if (br.readLine() == null) {
Toast.makeText(getApplicationContext(),"There are no contacts with Birthday details, try syncing with Facebook and/or Google", Toast.LENGTH_LONG).show();
DIALOG_SHOW = false;
}
}catch(Exception e){
System.out.println(e);
}
if(DIALOG_SHOW){
//Init the LoaderDialog
Asycdialog.setMessage("Working");
Asycdialog.getWindow().setGravity(Gravity.CENTER_VERTICAL);
Asycdialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
Asycdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Asycdialog.setCancelable(false);
//Dialog Show
Asycdialog.show();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = prefs.edit();
editor.putBoolean("async", true);
editor.commit();
super.onPreExecute();
}
protected void onPostExecute(String result) {
// hide the dialog
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, h:mm a");
String date = df.format(Calendar.getInstance().getTime());
SharedPreferences prefsx = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editorx = prefsx.edit();
editorx.putString("refresh", date);
editorx.commit();
dbHelper.close();
Asycdialog.dismiss();
startActivity(new Intent(LoaderClass.this, MainActivity.class));
finish();
super.onPostExecute(result);
}
#Override
protected String doInBackground(Void... args) {
dbHelper = new DBAdapter(getApplicationContext());
dbHelper.open();
int i=0;
int lines = 0;
// int prog = fetchAdhoc();
String progress = null;
String dateToInsert;
try{
BufferedReader reader;
if(FLAG ==1){
reader = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/xxxinders/fileone.txt"));
}else{
reader = new BufferedReader(new FileReader(getApplicationContext().getFilesDir()+"/xxxinders/output.txt"));
}
while (reader.readLine() != null) lines++;
reader.close();
}catch(Exception e){
}
Cursor c = dbHelper.fetchAdhoc();
ADHOC_COUNT = (c.getCount());
lines=lines+ADHOC_COUNT;
dbHelper.NotificationDrop();
if (c.moveToFirst()) {
do {
try{
String name = c.getString(c.getColumnIndexOrThrow("Name"));
String displayBirthday = c.getString(c.getColumnIndexOrThrow("DOB"));
String imageData = c.getString(c.getColumnIndexOrThrow("ImageData"));
String primaryAdhoc = c.getString(c.getColumnIndexOrThrow("_id"));
//CONTACT_ID,CONTACT_NAME,CONTACT_IMAGE_URI
CONTACT_ID = primaryAdhoc;
CONTACT_NAME = toTitleCase(name);
CONTACT_IMAGE_URI = imageData;
dateToInsert = displayBirthday;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dateToInsert);
java.sql.Date dx = new java.sql.Date(date.getTime());
Date key = dx;
years = getDiffYear(key); // For years elapsed
secon = seconds(key); // for seconds elapsed
min = seconds(key) / 60; // For minutes elapsed
hours = (int) (seconds(key) / 60) / 60; // For hours elapsed
mon = months(String.valueOf(key)); // for months elapsed
days = daysElapsed(key); // Days elapsed
weeks = daysElapsed(key) / 7; // For weeks
System.out.println(lines);
progress = ("" + (CONTACT_NAME) + "\n"+ i + " of " + lines + " Contacts");
dbHelper.insert(dateToInsert, CONTACT_NAME, String.valueOf(days), String.valueOf(hours), CONTACT_IMAGE_URI, String.valueOf(min),String.valueOf(mon), String.valueOf(secon), CONTACT_ID, String.valueOf(weeks), String.valueOf(years));
int PRIMARY_ID = dbHelper.getPrimaryId(); // Fetch the PrimaryId (_id) of the above inserted row, its the Foreign key for Notification and SpecialNotifications Table.
String FOREIGN_KEY = dbHelper.getHighestID(PRIMARY_ID); // Same as above, but fetches the Name field of the last inserted row.
//=========================================================================
//**Database Insertions Notifications Table/ SpecialNotifications Table**
//=========================================================================
//=======================================================================================//
//Regular intervals DB Insertions:
//======================================================================================//
//Notification Types:
//1 for months
//2 for weeks
//3 for days
//4 for minutes
//5 for years
//6 for seconds
//7 for hours
//======================================================================================//
//==============================
//For Months
//==============================
intCal.monthsNotify(mon, dateToInsert);
int monSpecial = intCal.getMonthRegular();
Date dateMonReg = intCal.getMonRegDate();
dbHelper.insertNotifications(1, convertDate(dateMonReg), 0, monSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For Weeks
//===============================
intCal.weeksToNotify(weeks,dateToInsert);
int weekSpecial = intCal.getWeekRegular();
Date dateWeekReg =intCal.getWeekRegDate();
dbHelper.insertNotifications(2, convertDate(dateWeekReg), 0, weekSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For Days
//===============================
intCal.daysToNotify(days, dateToInsert);
int daysSpecial= intCal.getDaysRegular();
Date dateDaysReg = intCal.getDaysRegDate();
dbHelper.insertNotifications(3, convertDate(dateDaysReg), 0, daysSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For minutes
//===============================
intCal.minutesToNotify(min,dateToInsert);
long minutesSpecial= intCal.getMinutesRegular();
Date dateMinsReg = intCal.getMinutesRegDate();
dbHelper.insertNotifications(4, convertDate(dateMinsReg), 0,(int) minutesSpecial,FOREIGN_KEY,PRIMARY_ID);
//==============================
//For Years
//==============================
intCal.yearsToNotify(years, dateToInsert);
int yearsSpecial = intCal.getYearsRegular();
Date dateYearsReg = intCal.getYearsRegDate();
dbHelper.insertNotifications(5, convertDate(dateYearsReg), 0, yearsSpecial,FOREIGN_KEY,PRIMARY_ID);
//=============================
//For Seconds
//=============================
intCal.secondsToNotify(secon, dateToInsert);
long secondsSpecial= intCal.getSecondsRegular();
Date dateSecondsReg = intCal.getSecondsRegDate();
dbHelper.insertNotifications(6, convertDate(dateSecondsReg), 0, secondsSpecial,FOREIGN_KEY,PRIMARY_ID);
//=============================
//For Hours
//=============================
intCal.hoursToNotify(hours, dateToInsert);
int hoursSpecial= intCal.getHoursRegular();
Date dateHoursReg= intCal.getHoursRegDate();
dbHelper.insertNotifications(7, convertDate(dateHoursReg), 0, hoursSpecial,FOREIGN_KEY,PRIMARY_ID);
//============================================================================================//
//Special Intervals
//============================================================================================//
//Notification Types:
//1 for months
//2 for weeks
//3 for days
//4 for minutes
//5 for years
//6 for seconds
//7 for hours
//For Years
intCal.specialIntervalYears(years, dateToInsert);
int yearsOnceSpecial =intCal.getYearsSpecial();
Date dateYearsSpecial = intCal.getYearsSpDate();
dbHelper.insertSpecialNotifications(5, convertDate(dateYearsSpecial), yearsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Months
intCal.specialIntervalMonths(mon,dateToInsert);
int monthsOnceSpecial= intCal.getMonthsSpecial();
Date dateMonthsSpecial = intCal.getMonthsSpDate();
dbHelper.insertSpecialNotifications(1, convertDate(dateMonthsSpecial), monthsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Weeks
intCal.specialIntervalsWeeks(weeks,dateToInsert);
int weeksOnceSpecial= intCal.getWeeksSpecial();
Date dateWeeksSpecial = intCal.getWeeksSpDate();
dbHelper.insertSpecialNotifications(2, convertDate(dateWeeksSpecial), weeksOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Days
intCal.specialIntervalsDays(days, dateToInsert);
int daysOnceSpecial= intCal.getDaysSpecial();
Date dateDaysSpecial = intCal.getDaysSpDate();
dbHelper.insertSpecialNotifications(3, convertDate(dateDaysSpecial), daysOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Hours
intCal.specialIntervalsHours(hours,dateToInsert);
int hoursOnceSpecial= intCal.getHoursSpecial();
Date dateHoursSpecial = intCal.getHoursSpDate();
dbHelper.insertSpecialNotifications(7, convertDate(dateHoursSpecial), hoursOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Minutes
intCal.specialIntervalMinutes(min,dateToInsert);
long minutesOnceSpecial= intCal.getMinutesSpecial();
Date dateMinutesSpecial= intCal.getMinutesSpDate();
dbHelper.insertSpecialNotifications(4, convertDate(dateMinutesSpecial), (int)minutesOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Seconds
intCal.specialIntervalsSeconds(secon,dateToInsert);
long secondsOnceSpecial= intCal.getSecondsSpecial();
Date dateSecondsSpecial= intCal.getSecondsSpDate();
dbHelper.insertSpecialNotifications(6, convertDate(dateSecondsSpecial), secondsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
i++;
}catch(Exception e){
}
publishProgress(progress);
Asycdialog.setMax(lines);
Asycdialog.incrementProgressBy(1);
}while(c.moveToNext());
}
//
// Dear maintainer:
//
// Once you are done trying to 'optimise' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 0;
//
//int i=0;
File toRead = null;
try{
if(FLAG ==1){
toRead=new File(getApplicationContext().getFilesDir()+"/xxxinders/fileone.txt");
}else{
toRead=new File(getApplicationContext().getFilesDir()+"/xxxinders/output.txt");
}
FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);
String currentLine;
while(sc.hasNextLine()){
currentLine=sc.nextLine();
StringTokenizer st=new StringTokenizer(currentLine,"=",false);
CONTACT_NAME = toTitleCase(st.nextToken());
if(CONTACT_NAME.contains("'")){
CONTACT_NAME = CONTACT_NAME.replace("'", "");
}
// *********
String listStr = st.nextToken();
String cut = listStr.substring(1, listStr.length() - 1);
String[] array = cut.split(",");
CONTACT_ID = (array[0].trim());
String dateStr = (array[1].trim());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dateStr);
java.sql.Date dx = new java.sql.Date(date.getTime());
Date key = dx;
dateToInsert = String.valueOf(dx);
CONTACT_IMAGE_URI = (array[2].trim());
if (isCancelled()) {
break;
}
progress = ("" + Character.toUpperCase(CONTACT_NAME.charAt(0)) + CONTACT_NAME.substring(1) + "\n"+i + " of " + lines + " Contacts"); // Progress displayed here.
years = getDiffYear(key); // For years elapsed
secon = seconds(key); // for seconds elapsed
min = seconds(key) / 60; // For minutes elapsed
hours = (int) (seconds(key) / 60) / 60; // For hours elapsed
mon = months(String.valueOf(key)); // for months elapsed
days = daysElapsed(key); // Days elapsed
weeks = daysElapsed(key) / 7; // For weeks
//===============================================================================================================
if (dateToInsert.contains("0001-") == true){ //Special Case, we added 0001 to Birthdays Which Have NO Year field.
//===========================================================================================================
dbHelper.insert(dateToInsert, CONTACT_NAME, "","", CONTACT_IMAGE_URI, "", "", "", CONTACT_ID, "", ""); // All other fields will be empty, because we don't have a Year.
int PRIMARY_ID = dbHelper.getPrimaryId();
String FOREIGN_KEY = dbHelper.getHighestID(PRIMARY_ID);
//=====================================================================================================
//In this case we are only interested in fetching the year alert for next birthday of this contact -->
//=====================================================================================================
intCal.yearsToNotify(years, dateToInsert);
int yearsSpecial = intCal.getYearsRegular();
Date dateYearsReg = intCal.getYearsRegDate();
dbHelper.insertNotifications(5, convertDate(dateYearsReg), 0, yearsSpecial,FOREIGN_KEY,PRIMARY_ID);
}
//=========================================================================
//Case when all the Date fields exist and we set up notifications --->
//=========================================================================
else if(dateToInsert != "null" && dateToInsert.contains("0001-") != true){
dbHelper.insert(dateToInsert, CONTACT_NAME, String.valueOf(days), String.valueOf(hours), CONTACT_IMAGE_URI, String.valueOf(min),String.valueOf(mon), String.valueOf(secon), CONTACT_ID, String.valueOf(weeks), String.valueOf(years));
int PRIMARY_ID = dbHelper.getPrimaryId(); // Fetch the PrimaryId (_id) of the above inserted row, its the Foreign key for Notification and SpecialNotifications Table.
String FOREIGN_KEY = dbHelper.getHighestID(PRIMARY_ID); // Same as above, but fetches the Name field of the last inserted row.
//=========================================================================
//**Database Insertions Notifications Table/ SpecialNotifications Table**
//=========================================================================
//=======================================================================================//
//Regular intervals DB Insertions:
//======================================================================================//
//Notification Types:
//1 for months
//2 for weeks
//3 for days
//4 for minutes
//5 for years
//6 for seconds
//7 for hours
//======================================================================================//
//==============================
//For Months
//==============================
intCal.monthsNotify(mon, dateToInsert);
int monSpecial = intCal.getMonthRegular();
Date dateMonReg = intCal.getMonRegDate();
dbHelper.insertNotifications(1, convertDate(dateMonReg), 0, monSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For Weeks
//===============================
intCal.weeksToNotify(weeks,dateToInsert);
int weekSpecial = intCal.getWeekRegular();
Date dateWeekReg =intCal.getWeekRegDate();
dbHelper.insertNotifications(2, convertDate(dateWeekReg), 0, weekSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For Days
//===============================
intCal.daysToNotify(days, dateToInsert);
int daysSpecial= intCal.getDaysRegular();
Date dateDaysReg = intCal.getDaysRegDate();
dbHelper.insertNotifications(3, convertDate(dateDaysReg), 0, daysSpecial,FOREIGN_KEY,PRIMARY_ID);
//===============================
//For minutes
//===============================
intCal.minutesToNotify(min,dateToInsert);
long minutesSpecial= intCal.getMinutesRegular();
Date dateMinsReg = intCal.getMinutesRegDate();
dbHelper.insertNotifications(4, convertDate(dateMinsReg), 0,(int) minutesSpecial,FOREIGN_KEY,PRIMARY_ID);
//==============================
//For Years
//==============================
intCal.yearsToNotify(years, dateToInsert);
int yearsSpecial = intCal.getYearsRegular();
Date dateYearsReg = intCal.getYearsRegDate();
dbHelper.insertNotifications(5, convertDate(dateYearsReg), 0, yearsSpecial,FOREIGN_KEY,PRIMARY_ID);
//=============================
//For Seconds
//=============================
intCal.secondsToNotify(secon, dateToInsert);
long secondsSpecial= intCal.getSecondsRegular();
Date dateSecondsReg = intCal.getSecondsRegDate();
dbHelper.insertNotifications(6, convertDate(dateSecondsReg), 0, secondsSpecial,FOREIGN_KEY,PRIMARY_ID);
//=============================
//For Hours
//=============================
intCal.hoursToNotify(hours, dateToInsert);
int hoursSpecial= intCal.getHoursRegular();
Date dateHoursReg= intCal.getHoursRegDate();
dbHelper.insertNotifications(7, convertDate(dateHoursReg), 0, hoursSpecial,FOREIGN_KEY,PRIMARY_ID);
//============================================================================================//
//Special Intervals
//============================================================================================//
//Notification Types:
//1 for months
//2 for weeks
//3 for days
//4 for minutes
//5 for years
//6 for seconds
//7 for hours
//For Years
intCal.specialIntervalYears(years, dateToInsert);
int yearsOnceSpecial =intCal.getYearsSpecial();
Date dateYearsSpecial = intCal.getYearsSpDate();
dbHelper.insertSpecialNotifications(5, convertDate(dateYearsSpecial), yearsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Months
intCal.specialIntervalMonths(mon,dateToInsert);
int monthsOnceSpecial= intCal.getMonthsSpecial();
Date dateMonthsSpecial = intCal.getMonthsSpDate();
dbHelper.insertSpecialNotifications(1, convertDate(dateMonthsSpecial), monthsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Weeks
intCal.specialIntervalsWeeks(weeks,dateToInsert);
int weeksOnceSpecial= intCal.getWeeksSpecial();
Date dateWeeksSpecial = intCal.getWeeksSpDate();
dbHelper.insertSpecialNotifications(2, convertDate(dateWeeksSpecial), weeksOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Days
intCal.specialIntervalsDays(days, dateToInsert);
int daysOnceSpecial= intCal.getDaysSpecial();
Date dateDaysSpecial = intCal.getDaysSpDate();
dbHelper.insertSpecialNotifications(3, convertDate(dateDaysSpecial), daysOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Hours
intCal.specialIntervalsHours(hours,dateToInsert);
int hoursOnceSpecial= intCal.getHoursSpecial();
Date dateHoursSpecial = intCal.getHoursSpDate();
dbHelper.insertSpecialNotifications(7, convertDate(dateHoursSpecial), hoursOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Minutes
intCal.specialIntervalMinutes(min,dateToInsert);
long minutesOnceSpecial= intCal.getMinutesSpecial();
Date dateMinutesSpecial= intCal.getMinutesSpDate();
dbHelper.insertSpecialNotifications(4, convertDate(dateMinutesSpecial), (int)minutesOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
//For Seconds
intCal.specialIntervalsSeconds(secon,dateToInsert);
long secondsOnceSpecial= intCal.getSecondsSpecial();
Date dateSecondsSpecial= intCal.getSecondsSpDate();
dbHelper.insertSpecialNotifications(6, convertDate(dateSecondsSpecial), secondsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
writeToSD();
}
publishProgress(progress);
Asycdialog.setMax(lines);
Asycdialog.incrementProgressBy(1);
i++;
}
writeToSD();
}catch (Exception e){
System.out.println(e);
} finally{
dbHelper.close();
}
return "";
}
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Asycdialog.setMessage("" + values[0]);
}
}
Edit: I found something useful Here
Test your ideas with this and this it allows you to check which part of your code is slow so you fix it.
You can store the informations in a local database instead a textfile. It should work much faster than with the textfile and you still can generate the textfile from the local database.
I am trying to check if the current time is in the range of a specified range. I made a method to check this, but it doesn't work. I'm not sure why not and how to get it to work.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime= Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
I am trying to test it like this:
if(checkTime("06:00-19:00")){
inRange = true;
}
The NPE is gone, but it's still not calculating if the time is in the range of fromTime to toTime. Any help is very much appreciated!
Initialize variables and change the return type of your method to boolean.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
You have not initialized toTime and fromTime objects before using them. So better call toTime = Calendar.getInstance(); before.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
this
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
Doesn't do what you would like it to do. What it does is set the field HOUR to the value of Calendar.HOUR, which is an arbitrary constant.
You don't need those 2 lines as getInstance returns a Calendar at the current time.
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//cal.add(Calendar.DATE, 1);
String date = sdf.format(cal.getTime());
String dateStart = date+" "+"11:30:00";
String date2 = sdf.format(cal2.getTime());
String dateStop = date2+" "+"23:00:00";
Calendar calendar = Calendar.getInstance();
String currentTime = format.format(calendar.getTime());
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(currentTime);
// Toast.makeText(getApplicationContext(),""+dateCal,Toast.LENGTH_SHORT).show();
if (d3.before(d2)
&& d3.after(d1) ){}else{} } catch (ParseException e) {
e.printStackTrace();
}
Put currentTime outside of setTime and remove if-statement from setTime.
If you need put if-statement outside of setTime.
private boolean checkBedTime(String time) {
// Time Pattern Like : "06:00-19:00"
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
int fromHour = Integer.parseInt(from[0]);
int fromMinute = Integer.parseInt(from[1]);
int toHour = Integer.parseInt(until[0]);
int toMinute = Integer.parseInt(until[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int convertedFromMinute = (fromHour * 60) + fromMinute;
int convertedToMinute = (toHour * 60) + toMinute;
int convertedCurrentMinute = (currentHour * 60) + currentMinute;
if (convertedFromMinute == convertedToMinute) {
Toast.makeText(context, "Sleep Time & Wake Up Time can't be same", Toast.LENGTH_SHORT).show();
return false;
} else if (convertedToMinute < convertedFromMinute) {
convertedToMinute = convertedToMinute + (24 * 60);
}
Log.v("Time", "FromMinute --> " + convertedFromMinute);
Log.v("Time", "ToMinute --> " + convertedToMinute);
Log.v("Time", "CurrentMinute -- > " + convertedCurrentMinute);
if (convertedCurrentMinute >= convertedFromMinute && convertedCurrentMinute <= convertedToMinute) {
return true;
} else {
return false;
}
}