Android app not responding at Calender.getInstance - java

I am trying to get date doing calculations. For that I'm using Calendar cal = Calendar.getInstance();I am using this import import java.util.Calendar; When the app comes to onResume I am calling a method. In that method, the first line is getting Instance(). But for some reason, I am getting this error(ANR).
at java.util.Calendar.getInstance(Calendar.java:960)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:231)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:330)
at java.util.Calendar.<init>(Calendar.java:718)
at java.util.Calendar.<init>(Calendar.java:712)
Caused by: com.github.anrwatchdog.ANRError$$$_Thread: main
Caused by: com.github.anrwatchdog.ANRError: Application Not Responding
at com.github.anrwatchdog.ANRWatchDog.void run()(SourceFile:212)
at com.splunk.mint.Mint$3.void onAppNotResponding(com.github.anrwatchdog.ANRError)(SourceFile:297)
java.lang.Exception: com.github.anrwatchdog.ANRError: Application Not Responding
EDIT (adding code as asked)
public static int getCategory(final String time) {
long thenTime = SDKUtils.getLong(getLongValue(time));
Calendar c1 = Calendar.getInstance(); // today
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date(thenTime)); // your date
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return TODAY;
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return YESTERDAY;
c1 = Calendar.getInstance();
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) )
return MONTH;
else
return YEAR;
}
public static String[] getSubTime(final String time, final int category) {
Calendar cal = Calendar.getInstance();
Date date = new Date(SDKUtils.getLong(getLongValue(time)));
TimeZone tz = TimeZone.getDefault();
cal.setTime(date);
cal.setTimeZone(tz);
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 12)
hour = hour - 12;
int min = cal.get(Calendar.MINUTE);
String hourStr = hour < 10 ? "0" + hour : "" + hour;
String minStr = min < 10 ? "0" + min : "" + min;
String am = cal.get(Calendar.HOUR_OF_DAY) < 12 ? " AM" : " PM";
switch (category) {
case TODAY:
case YESTERDAY: {
return new String[] { hourStr + ":" + minStr + "", am };
}
case MONTH: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
case DATE: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
default: {
String month = convertNumberToMonthMMM(cal.get(Calendar.MONTH));
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { month + " " + dateString, ", " + hourStr + ":" + minStr + "" + am };
}
}
}
These are the two methods i call. what is wrong?

Why you not try:
public class MainActivity extends AppCompatActivity
{
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}
Edit:
I think you're using:
import java.util.GregorianCalendar;
You try (add or) instead of:
import java.util.Calendar;
Regards

Related

How to get Time Slot based on 1hour interval

I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}
Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.
try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}

Get available days between two days in java

I am newly for java, and i want to build booking system and now i try to get available days between two days without booked days. but, however my code running bad.
this is my code
Connection connection = DBConnection.getInstance().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from A");
ResultSet executeQuery = preparedStatement.executeQuery();
while (executeQuery.next()) {
String refid = executeQuery.getString("REFID");
statDate = executeQuery.getDate("Start_date");
endDate = executeQuery.getDate("End_date");
System.out.println("ref no : " + refid + " statDate :" + statDate + " end date :" + endDate);
System.out.println("\n");
int month = statDate.getMonth();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
String format = df.format(cal.getTime());
dateOfMonth.add(format);
addDays = addDays(statDate, 2);
if (df.format(cal.getTime()).equals("" + statDate) || df.format(cal.getTime()).equals("" + endDate)) {
//System.out.println(statDate + " is not available !");
System.out.println("---");
} else {
int bDays = endDate.getDate() - statDate.getDate();
//System.out.println(bDays);
//===========
List<DateTime> between = getDateRange(DateTime.parse(statDate.toString()), DateTime.parse(endDate.toString()));
for (DateTime dateTime : between) {
Date da = dateTime.toDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dateOfBooked.add(sdf.format(da));
}
System.out.println(df.format(cal.getTime()));
}
}
System.out.println("\n");
}
this is my db script
insert into A values('1','ref1','2018-02-18','2018-02-25');
insert into A values('2','ref1','2018-03-10','2018-03-17');
insert into A values('3','ref1','2018-03-20','2018-03-27');
i try to get available days from thees booked days. how can i print only available days ?
output

My DatePicker cannot setText() to textView at first try

I got this problem cause my DatePicker not set text to textView on first try but after first try it can set without any problem.
This is my setDate Function, it will work after click at Linearlayout.
public void setBirthDate(){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(calendar.MONTH);
int day = calendar.get(calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog( setting.this,
datePickerDialog,
year, month, day);
dialog.getWindow();
dialog.show();
datePickerDialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month += 1;
String date = null;
if (month < 10) {
if (day < 10) {
date = "0" + day + "/" + "0" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + "0" + month + "/" + year;
}
} else if (month >= 10) {
if (day < 10) {
date = "0" + day + "/" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + month + "/" + year;
}
}
Toast.makeText(setting.this, date, Toast.LENGTH_SHORT).show();
textView_birthdate.setText(date);
}
};
}
And this is how I handle event.
#Override
public void onClick(View v){
if(v.getId() == R.id.settinglo_birthdate){
setBirthDate();
}
else if(){}
...
...
...
}
This is my onCreate
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_02);
list_linear = new ArrayList<>();
list_textview = new ArrayList<>();
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.settingtb);
toolbar.setCollapsible(true);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Setting");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
initialVIew();
}
This is initialView() method
public void initialVIew(){
/* layout initial & add to list */
list_linear.add(linear_fname = (LinearLayout) findViewById(R.id.settinglo_fname));
list_linear.add(linear_lname = (LinearLayout) findViewById(R.id.settinglo_lname));
list_linear.add(linear_birthdate = (LinearLayout) findViewById(R.id.settinglo_birthdate));
list_linear.add(linear_gender = (LinearLayout) findViewById(R.id.settinglo_gender));
list_linear.add(linear_tel = (LinearLayout) findViewById(R.id.settinglo_tel));
list_linear.add(linear_carefname = (LinearLayout) findViewById(R.id.settinglo_c_fname) );
list_linear.add(linear_carelname = (LinearLayout) findViewById(R.id.settinglo_c_lname) );
list_linear.add(linear_careemail = (LinearLayout) findViewById(R.id.settinglo_c_email) );
list_linear.add(linear_caretel = (LinearLayout) findViewById(R.id.settinglo_c_tel) );
list_linear.add(linear_min = (LinearLayout) findViewById(R.id.settinglo_glucose_min) );
list_linear.add(linear_max = (LinearLayout) findViewById(R.id.settinglo_glucose_max) );
/* textView initial & add to list */
list_textview.add(textView_fname = (TextView) findViewById(R.id.settingtv_fname));
list_textview.add(textView_lname = (TextView) findViewById(R.id.settingtv_lname));
list_textview.add(textView_birthdate = (TextView) findViewById(R.id.settingtv_birthdate));
list_textview.add(textView_gender = (TextView) findViewById(R.id.settingtv_gender));
list_textview.add(textView_tel = (TextView) findViewById(R.id.settingtv_tel));
list_textview.add(textView_carefname = (TextView) findViewById(R.id.settingtv_c_fname) );
list_textview.add(textView_carelname = (TextView) findViewById(R.id.settingtv_c_lname) );
list_textview.add(textView_careemail = (TextView) findViewById(R.id.settingtv_c_email) );
list_textview.add(textView_caretel = (TextView) findViewById(R.id.settingtv_c_tel) );
list_textview.add(textView_min = (TextView) findViewById(R.id.settingtv_glucose_min) );
list_textview.add(textView_max = (TextView) findViewById(R.id.settingtv_glucose_max) );
// layout set event
for(LinearLayout linearLayout : list_linear){
linearLayout.setOnClickListener(this);
}
// textView set event
for(TextView textView : list_textview){
textView.setOnClickListener(this);
}
}
Now I'm got confuse with this other onClick on other LinearLayout work fine without any problem. Only setDate that not first on first time.
You should modify the setBirthDate() like this below:-
You should initiate the new DatePickerDialog.OnDateSetListener() first before initialising new DatePickerDialog()
public void setBirthDate(){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(calendar.MONTH);
int day = calendar.get(calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month += 1;
String date = null;
if (month < 10) {
if (day < 10) {
date = "0" + day + "/" + "0" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + "0" + month + "/" + year;
}
} else if (month >= 10) {
if (day < 10) {
date = "0" + day + "/" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + month + "/" + year;
}
}
Toast.makeText(SimpleActivity.this, date, Toast.LENGTH_SHORT).show();
textView_birthdate.setText(date);
}
};
DatePickerDialog dialog = new DatePickerDialog( SimpleActivity.this,
datePickerDialog,
year, month, day);
dialog.getWindow();
dialog.show();
}

How to get first and last date of weeks on basis of month and year in android

how to get first and last date of weeks on basis of month and year in android
ex:we pass month and year (March,2016) then i want all weeks just like
mar5- mar11,(sat to fri)
mar12- mar18,
mar19- mar25,
mar26-april01
please help me
Call this function to get results in a valid week pair list of given month of a year.
ex: getWeekStartEnd("December","2016");
Result: [
December3-December9,
December10-December16,
December17-December23,
December24-December30
]
List<String> getWeekStartEnd (String month , String year) {
List<String> validWeekPairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMMM-yyyy");
String day = "01";
try {
Date date = sdf.parse(day + "-" + month + "-" + year);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.SATURDAY);
List<String> startDayOfWeek = new ArrayList<>();
List<String> endDayOfWeek = new ArrayList<>();
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
boolean isStartDaySet = false;
boolean hasLastDayOfWeek = true;
for (int currentDay = 01; currentDay <= daysInMonth; currentDay++) {
Date newDate = sdf.parse(currentDay + "-" + month + "-" + year);
calendar.setTime(newDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
if (hasLastDayOfWeek) {
startDayOfWeek.add(month + String.valueOf(currentDay));
isStartDaySet = true;
hasLastDayOfWeek = false;
}
} else if (dayOfWeek == Calendar.FRIDAY) {
if (isStartDaySet) {
endDayOfWeek.add(month + String.valueOf(currentDay));
hasLastDayOfWeek = true;
}
}
}
for (int i = 0; i < endDayOfWeek.size(); i++) {
validWeekPairs.add(startDayOfWeek.get(i) + "-" + endDayOfWeek.get(i));
}
return validWeekPairs;
} catch (ParseException e) {
e.printStackTrace();
return validWeekPairs;
}catch (Exception e){
e.printStackTrace();
return validWeekPairs;
}
}
If you are using java.util.Date you can use the method getDay(). It returns Calendar constant, like Calendar.MONDAY.
You can pass the string as 02,2016
List<String> getWeekendsOftheMonth(String monthYearString) {
long monthDate;
List<String> weekEnds = new ArrayList<>();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd,MM,yyyy");
try {
monthYearString="01,".concat(monthYearString);
monthDate = simpleDateFormat.parse(monthYearString).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(monthDate);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
int minDate = calendar.getActualMinimum(Calendar.DATE);
for (int i = minDate; i <= maxDate; i++) {
calendar.set(Calendar.DATE, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
weekEnds.add(convertToDate(calendar.getTimeInMillis()));
}
}
}catch (Exception e){
e.printStackTrace();
}
return weekEnds;
}
String convertToDate(Long datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM. yyyy");
Date date = new Date(datetime);
return simpleDateFormat.format(date);
}
you can do it from this method.

Error with Joda DateTime Formatter

I have a class DurationFormatter as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class DurationFormatter {
private final static PeriodFormatter DURATION_FORMATTER =
new PeriodFormatterBuilder().appendYears()
.appendSuffix("year", "years")
.appendSeparator(" ")
.appendMonths()
.appendSuffix("month", "months")
.appendSeparator(" ")
.appendDays()
.appendSuffix("day", "days")
.appendSeparator(" ")
.appendHours()
.appendSuffix("hour", "hours")
.appendSeparator(" ")
.appendMinutes()
.appendSuffix("minute", "minutes")
.appendSeparator(" ")
.appendSeconds()
.appendSuffix("second", "seconds")
.toFormatter();
public static String format(Date start) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start), new DateTime()));
return result.toString();
}
public static String format(Date start, Date end) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start),
end == null
? new DateTime()
: new DateTime(end)));
return result.toString();
}
}
And this is my Unit Test:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.junit.Test;
public class DurationFormatterTest {
#Test
public void testFormatDate() throws ParseException {
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateString = "07/27/2010 12:07:34";
Date startDate = (Date) df.parse( dateString );
// Find duration 1
String duration1 = DurationFormatter.format(startDate);
// Parse duration 1 and set values into new Period
String[] tokens = duration1.split("[ ]");
for( int index = 0; index < tokens.length; index++ ) {
String token = tokens[index];
if( token.contains("years") ) {
years = Integer.valueOf(token.replace("years", ""));
System.out.println("Years are: " + years);
}
else if( token.contains("months") ) {
months = Integer.valueOf(token.replace("months", ""));
System.out.println("Months are: " + months);
}
else if( token.contains("days") ) {
days = Integer.valueOf(token.replace("days", ""));
System.out.println("Days are: " + days);
}
else if( token.contains("hours") ) {
hours = Integer.valueOf(token.replace("hours", ""));
}
else if( token.contains("minutes") ) {
minutes = Integer.valueOf(token.replace("minutes", ""));
}
else if( token.contains("seconds") ) {
seconds = Integer.valueOf(token.replace("seconds", ""));
}
}
Period period = new Period( years, months, weeks, days, hours, minutes, seconds, 0);
// User period to initialize new endDate
DateTime endDate = new DateTime(startDate).plus(period);
// Find duration 2 using new endDate
String duration2 = DurationFormatter.format(startDate, endDate.toDate());
// If the durations are the same, then success.
Assert.assertEquals(
"The date of " + duration2
+ " is equal to " + duration1,
duration1, duration2);
}
}
The result always output with error:
junit.framework.ComparisonFailure:
The date of 5days 23hours 5minutes 23seconds is equal to 1month 5days 23hours 5minutes 23seconds expected:<[1month ]5days 23hours 5minut...> but was:<[]5days 23hours 5minut...>
The string '[1month ]' always missing. Please check if I'm missing something in code?
Thanks
In your code, you have .appendSuffix("month", "months") where "month" is the singular form, "months" is the plural form.
Your test only parses the plural forms:
else if( token.contains("months") ) {
...
}
In this case, the test fails because it is only 1 month and therefore singular.
Update your testing code to parse both singular and plural form and it should work!
Documentation

Categories

Resources