I have a class with three pairs of Date fields.
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
public Filter(Date startDateFrom, Date startDateTo,
Date endDateFrom, Date endDateTo,
Date regDateFrom, Date regDateTo) {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
}
}
So I need to check that at least one pair has both not null Dates and check that DateFrom is before or equals DateTo for all not-null dates.
I've made this to check if there is at least one pair:
public boolean allDatesMissing() {
if (startDateFrom != null && startDateTo != null) {
return false;
} else if (endDateFrom != null && endDateTo != null) {
return false;
} else if (regDateFrom != null && regDateTo != null) {
return false;
}
return true;
}
And this to check fromDate is before toDate:
public void checkDates(Date from, Date to) throws RequestException{
if (from != null) {
if (to != null) {
if (from.after(to)) {
throw new MyException(INCORRECT_DATES_PERIOD);
}
} else {
throw new MyException(MISSING_PARAMETER);
}
} else if (to != null){
throw new MyException(MISSING_PARAMETER);
}
}
Is there any simplier way to do the same?
You have declared the Filter class static..Then it should be a inner class..
package demo;
import java.util.Date;
public class FilterDemo {
public static void main(String[] args) throws Exception {
Filter f = new Filter(new Date(2017, 01, 01), new Date(2017, 02, 01),
null, null, null, null);
}
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
// dateCounter will maintain the count of correct date pair
public static int dateCount = 0;
public Filter(Date startDateFrom, Date startDateTo, Date endDateFrom,
Date endDateTo, Date regDateFrom, Date regDateTo)
throws Exception {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
isExist(startDateFrom, startDateTo);
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
isExist(endDateFrom, endDateTo);
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
isExist(regDateFrom, regDateTo);
// throw exception after initializing 3 pair,if count is still 0
if (dateCount == 0)
throw new Exception("All pairs are null");
}
public static void isExist(Date from, Date to) throws Exception {
if (from != null && to != null) {
checkDates(from, to);
}
}
public static void checkDates(Date from, Date to) throws Exception {
if (from.getTime() > to.getTime()) {
throw new Exception("INCORRECT_DATES_PERIOD");
}
//increase dateCount if date pair is correct
dateCount++;
}
}
}
I have a JSON file placed in the server which describes one academic week schedule of a class. I have to request for it using Volley. Later I need to serialize the returned JSON object individually and create multiple events for that particular month.
But when I run the application, Volley returns onErrorResponse. When I try doing the same with Retrofit, it worked fine but the output is not as expected.
IT-3-2.json
[{"schedule_of":"IT-3-2","day":"1","from_time":"09:55","to_time":"10:45","subject":"CC","details":"manasa"},
{"schedule_of":"IT-3-2","day":"1","from_time":"10:45","to_time":"11:35","subject":"CC","details":"manasa"},
{"schedule_of":"IT-3-2","day":"1","from_time":"11:35","to_time":"12:25","subject":"WT","details":"asha"},
{"schedule_of":"IT-3-2","day":"1","from_time":"12:25","to_time":"13:15","subject":"WT","details":"asha"},
{"schedule_of":"IT-3-2","day":"1","from_time":"14:15","to_time":"15:05","subject":"ACS lab","details":"gouthami"},
{"schedule_of":"IT-3-2","day":"1","from_time":"15:05","to_time":"15:55","subject":"ACS lab","details":"gouthami"},
{"schedule_of":"IT-3-2","day":"1","from_time":"15:55","to_time":"16:45","subject":"ACS lab","details":"gouthami"},
{"schedule_of":"IT-3-2","day":"2","from_time":"09:55","to_time":"10:45","subject":"IPR","details":"samreen"},
{"schedule_of":"IT-3-2","day":"2","from_time":"10:45","to_time":"11:35","subject":"IPR","details":"samreen"},
{"schedule_of":"IT-3-2","day":"2","from_time":"11:35","to_time":"12:25","subject":"WT","details":"asha"},
{"schedule_of":"IT-3-2","day":"2","from_time":"12:25","to_time":"13:15","subject":"WT","details":"asha"},
{"schedule_of":"IT-3-2","day":"2","from_time":"14:15","to_time":"15:05","subject":"WT lab","details":"rajesh"},
{"schedule_of":"IT-3-2","day":"2","from_time":"15:05","to_time":"15:55","subject":"WT lab","details":"rajesh"},
{"schedule_of":"IT-3-2","day":"2","from_time":"15:55","to_time":"16:45","subject":"WT lab","details":"rajesh"},
{"schedule_of":"IT-3-2","day":"3","from_time":"09:55","to_time":"10:45","subject":"DWDM","details":"shashikanth"},
{"schedule_of":"IT-3-2","day":"3","from_time":"10:45","to_time":"11:35","subject":"DWDM","details":"shashikanth"},{"schedule_of":"IT-3-2","day":"3","from_time":"11:35","to_time":"12:25","subject":"OOAD","details":"madhukar"},{"schedule_of":"IT-3-2","day":"3","from_time":"12:25","to_time":"13:15","subject":"OOAD","details":"madhukar"},{"schedule_of":"IT-3-2","day":"4","from_time":"09:55","to_time":"10:45","subject":"STM","details":"harikrishna"},{"schedule_of":"IT-3-2","day":"4","from_time":"10:45","to_time":"11:35","subject":"STM","details":"harikrishna"},{"schedule_of":"IT-3-2","day":"4","from_time":"11:35","to_time":"12:25","subject":"OOAD","details":"shashikanth"},{"schedule_of":"IT-3-2","day":"4","from_time":"12:25","to_time":"13:15","subject":"OOAD","details":"shashikanth"},{"schedule_of":"IT-3-2","day":"4","from_time":"14:15","to_time":"15:05","subject":"DWDM","details":"shashikanth"},{"schedule_of":"IT-3-2","day":"4","from_time":"15:05","to_time":"15:55","subject":"DWDM","details":"shashikanth"},{"schedule_of":"IT-3-2","day":"5","from_time":"09:55","to_time":"10:45","subject":"IPR","details":"samreen"},{"schedule_of":"IT-3-2","day":"5","from_time":"10:45","to_time":"11:35","subject":"IPR","details":"samreen"},{"schedule_of":"IT-3-2","day":"5","from_time":"11:35","to_time":"12:25","subject":"STM","details":"harikrishna"},{"schedule_of":"IT-3-2","day":"5","from_time":"12:25","to_time":"13:15","subject":"STM","details":"harikrishna"},{"schedule_of":"IT-3-2","day":"5","from_time":"14:15","to_time":"15:05","subject":"CC","details":"manasa"},{"schedule_of":"IT-3-2","day":"5","from_time":"15:05","to_time":"15:55","subject":"CC","details":"manasa"}]
AsynchronousActivity.java
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
visibleMonth = newMonth;
visibleYear = newYear;
Log.d(TAG, "month changed - "+newMonth);
final String URL = "http://192.168.0.5/practice/schedule/jsons/IT-3-2.json";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL,null /*new JSONObject(params)*/,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
VolleyLog.v("Response:%n %s", response);
makeWeeklyEvents((List<WeeklyEvent>) gson.fromJson(response.toString(),WeeklyEvent.class) );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
//AppController.getInstance().addToRequestQueue(req);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(req);
// Return only the events that matches newYear and newMonth.
List<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : events) {
if (eventMatches(event, newYear, newMonth)) {
matchedEvents.add(event);
}
}
return matchedEvents;
}
public void makeWeeklyEvents(List<WeeklyEvent> events){
this.events.clear();
for (WeeklyEvent event : events) {
this.events.addAll(event.toWeekViewEvent());
Log.d(TAG, "size of events : "+this.events.size());
}
getWeekView().notifyDatasetChanged();
}
weeklyEvent.java
public class WeeklyEvent {
private static final String TAG = WeeklyEvent.class.getSimpleName();
#Expose
#SerializedName("subject")
private String mName;
#Expose #SerializedName("day")
private int mDay;
#Expose #SerializedName("from_time")
private String mStartTime;
#Expose #SerializedName("to_time")
private String mEndTime;
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getDay() {
return mDay;
}
public void setDay(int day) {
this.mDay = day;
}
public String getStartTime() {
return mStartTime;
}
public void setStartTime(String startTime) {
this.mStartTime = startTime;
}
public String getEndTime() {
return mEndTime;
}
public void setEndTime(String endTime) {
this.mEndTime = endTime;
}
#SuppressLint("SimpleDateFormat")
public ArrayList<WeekViewEvent> toWeekViewEvent(){
// Parse time.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date start = new Date();
Date end = new Date();
try {
start = sdf.parse(getStartTime());
} catch (ParseException e) {
e.printStackTrace();
}
try {
end = sdf.parse(getEndTime());
} catch (ParseException e) {
e.printStackTrace();
}
// Initialize start and end time.
Calendar now = Calendar.getInstance();
// Create an week view event.
ArrayList<WeekViewEvent> list = new ArrayList<WeekViewEvent>();
// Create a WeekViewEvent holder
WeekViewEvent weekViewEvent = new WeekViewEvent();
for(int i= getFirstDay(1,AsynchronousActivity.visibleMonth,AsynchronousActivity.visibleYear) - getDay(); i<now.getActualMaximum(Calendar.DAY_OF_MONTH);i+=7 ){
Calendar startTime = (Calendar) now.clone();
startTime.setTimeInMillis(start.getTime());
startTime.set(Calendar.YEAR, AsynchronousActivity.visibleYear);
startTime.set(Calendar.MONTH, AsynchronousActivity.visibleMonth);
startTime.set(Calendar.DAY_OF_MONTH, i);
Calendar endTime = (Calendar) startTime.clone();
endTime.setTimeInMillis(end.getTime());
endTime.set(Calendar.YEAR, AsynchronousActivity.visibleYear);
endTime.set(Calendar.MONTH, AsynchronousActivity.visibleMonth);
endTime.set(Calendar.DAY_OF_MONTH, i);
// Set values into event.
weekViewEvent.setName(getName());
weekViewEvent.setStartTime(startTime);
weekViewEvent.setEndTime(endTime);
weekViewEvent.setColor(Color.GREEN);
Log.d(TAG, "weekly event recieved : "+getName()+", time : "+weekViewEvent.getStartTime().getTimeInMillis() +" - "+weekViewEvent.getEndTime().getTimeInMillis());
// Append WeekViewEvent to the list.
list.add(weekViewEvent);
}
Log.d(TAG, "list is updating "+list.size()+" events.");
return list;
}
public int getFirstDay(int day, int month, int year)
{
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DATE, day);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, 1);
switch (cal.get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
return 0;
case Calendar.TUESDAY:
return 1;
case Calendar.WEDNESDAY:
return 2;
case Calendar.THURSDAY:
return 3;
case Calendar.FRIDAY:
return 4;
case Calendar.SATURDAY:
return 5;
case Calendar.SUNDAY:
return 6;
}
return -1;
}
}
Running the application, it returns the follow Volley error: screenshot of logcat
JSON file is accessible when I try the same URL link from the device browser.
When I tried doing the same with Retrofit, it successfully retrieved and processed the JSON but the output was not as expected.
if (!calledNetwork) {
RestAdapter retrofit = new RestAdapter.Builder()
.setEndpoint("http://192.168.0.5")
.build();
MyJsonService service = retrofit.create(MyJsonService.class);
service.listWeekEvents(this);
calledNetwork = true;
MyJsonService.java
public interface MyJsonService {
#GET("/practice/schedule/jsons/IT-3-2.json")
//http://192.168.0.5/practice/schedule/jsons/IT-3-2.json
void listWeekEvents(Callback<List<WeeklyEvent>> weeklyEventsCallback);
}
The functionality is that, I need to duplicate the input event- JsonObject (it contains "day"-day_of_week which represents that event occurs every week on that day) to all that particular day of every week in one month.
for(int i= getFirstDay(1,AsynchronousActivity.visibleMonth,AsynchronousActivity.visibleYear) - getDay(); i<now.getActualMaximum(Calendar.DAY_OF_MONTH);i+=7 ){
Calendar startTime = (Calendar) now.clone();
startTime.setTimeInMillis(start.getTime());
startTime.set(Calendar.YEAR, AsynchronousActivity.visibleYear);
startTime.set(Calendar.MONTH, AsynchronousActivity.visibleMonth);
startTime.set(Calendar.DAY_OF_MONTH, i);
Calendar endTime = (Calendar) startTime.clone();
endTime.setTimeInMillis(end.getTime());
endTime.set(Calendar.YEAR, AsynchronousActivity.visibleYear);
endTime.set(Calendar.MONTH, AsynchronousActivity.visibleMonth);
endTime.set(Calendar.DAY_OF_MONTH, i);
// Set values into event.
weekViewEvent.setName(getName());
weekViewEvent.setStartTime(startTime);
weekViewEvent.setEndTime(endTime);
weekViewEvent.setColor(Color.GREEN);
Log.d(TAG, "weekly event recieved : "+getName()+", time : "+weekViewEvent.getStartTime().getTimeInMillis() +" - "+weekViewEvent.getEndTime().getTimeInMillis());
// Append WeekViewEvent to the list.
list.add(weekViewEvent);
}
When the application is runned (on 14th Feb,2017), the events are shown only from 24th Feb,2017 - 28th Feb,2017. and that to all the duplicate events generated are shown in one day itself.
screenshot of the application showing 26th Feb,2017 while runned with retrofit
I have been using alamkanak/Android-Week-View (link will be posted in answers section if wanted, as more then 2 links can't be posted for now) library to display the events.
Please, help me to solve this problem. Thanks in advance.
i have these two parts of code.
Adding to the arraylist doesn't work, f arrylist is always empty. In the output debug window, the only message that i receive is Unparseable date: "2014-12-09 00:00:00.0" for each Fattura.
private ArrayList<Fattura> getFatture() throws SQLException {
String localDb;
String unformattedQuery;
ArrayList<Fattura> ftt = new ArrayList<Fattura>();
if (this.serviceSelection.getSelectedItem() == "Energia") {
localDb = EmailCheckerGUI.DbEnergia;
unformattedQuery = ServiceQuery.RECUPERAFATTUREENERGIA.getQuery();
} else {
localDb = EmailCheckerGUI.DbGas;
unformattedQuery = ServiceQuery.RECUPERAFATTUREGAS.getQuery();
}
DbHandlerContext db = new DbHandlerContext(new SqlServerConcrete(EmailCheckerGUI.user, EmailCheckerGUI.pwd, localDb));
String formattedQuery = String.format(unformattedQuery,
BillIntervalContainer.getFormattedMinDataFatt("MM/dd/yyyy"),
BillIntervalContainer.getFormattedMaxDataFatt("MM/dd/yyyy"),
BillIntervalContainer.minFattNumber, BillIntervalContainer.maxFattNumber);
ResultSet r = db.executeQuery(formattedQuery);
while (r.next()) {
try {
boolean addingelement = false;
String ioError = "";
try {
addingelement = ftt.add(new Fattura(r.getInt("id"), r.getString("servizio"), r.getString("email"),
r.getString("denominazione"), r.getString("data_fattura"), r.getString("data_scadenza"), r.getString("path_fattura"),
r.getInt("inviato"), r.getString("report"), r.getInt("numero_fattura"), r.getInt("id_documento")));
} catch (IOException ex) {
Logger.getLogger(EmailCheckerGUI.class.getName()).log(Level.SEVERE, null, ex);
ioError = ex.getMessage();
}
if (!addingelement) {
if (!"".equals(ioError)) {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura"));
} else {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura") + ": " + ioError);
}
} else {
System.out.println(r.getString("numero_fattura"));
}
} catch (ParseException ex) {
System.out.println(ex.getMessage());
}
}
return ftt;
}
and
Fattura( int id, String service, String email,
String name, String dateBill, String dateScad, String path,
int sent, String report, int billNumber, int idDocument) throws ParseException, IOException{
this.id = id;
this.service = service;
this.email = email;
this.name = name;
this.path = path;
this.report = report;
this.sent = sent;
this.billNumber = billNumber;
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").parse(dateBill);
this.dateScad = new SimpleDateFormat("yyyy-MM-dd").parse(dateScad);
this.idDocument = idDocument;
this.pdfDocument = new PdfValidator(null, this.name, dateBill, String.valueOf(this.billNumber), String.valueOf(0), this.path);
}
Any idea of where i'm wrong?
Thanks
You are using week year : YYYY instead of year yyyy. Please take a look at the SimpleDateFormat documentation. You'll find all the patterns and some usefull examples.
Now yyyy-MM-dd will only parse 2014-12-09. If you have also time after date you should use something like :
yyyy-MM-dd HH:mm:ss.S
Or You can use .format instead of .parse :
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
but watch out that MM can't be lowercase.