List of usage examples for java.util Date setMonth
@Deprecated public void setMonth(int month)
From source file:eu.inmite.apps.smsjizdenka.util.SmsParser.java
private Date parseDate(String text, String datePattern, SimpleDateFormat sdf, SimpleDateFormat sdfTime, Ticket ticket) {/*from w w w.j a v a 2 s . co m*/ Matcher m = Pattern.compile(datePattern).matcher(text); if (m.find()) { String d = m.group(1); if (!isEmpty(d)) { d = d.replaceAll(";", ""); for (int i = 0; i < 2; i++) { final Date date; try { if (i == 0) { date = sdf.parse(d); // full date/time } else if (i == 1 && sdfTime != null) { date = sdfTime.parse(d); // only time } else { break; } } catch (Exception e) { continue; } if (i == 1 && ticket != null && ticket.validFrom != null) { final Date prevDate = ticket.validFrom; date.setYear(prevDate.getYear()); date.setMonth(prevDate.getMonth()); date.setDate(prevDate.getDate()); } return date; } } } throw new RuntimeException("Cannot parse date from the message " + text); }
From source file:com.fitforbusiness.nafc.dashboard.DashBoardFragment.java
private void loadSessions(String date) { Calendar calendar = Calendar.getInstance(); date = String.format("%d-%02d-%02d", calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) + 1), calendar.get(Calendar.DAY_OF_MONTH)); Date stDate = null;/*w ww . j a v a2 s.c om*/ Date edDate = null; try { stDate = new SimpleDateFormat("yyyy-MM-dd").parse(date); stDate.setTime(stDate.getTime() - 1000); edDate = new SimpleDateFormat("yyyy-MM-dd").parse(date); edDate.setTime(edDate.getTime() + (24 * 60 * 60 * 1000)); edDate.setTime(edDate.getTime() - 1000); } catch (Exception e) { e.printStackTrace(); return; } ArrayList<HashMap<String, Object>> mapArrayList = new ArrayList<>(); SQLiteDatabase sqlDB; try { sqlDB = DatabaseHelper.instance().getReadableDatabase(); String query = "select " + Table.Sessions.ID + " , " + Table.Sessions.START_DATE + " , " + Table.Sessions.START_TIME + " , " + Table.Sessions.SESSION_STATUS + " , " + Table.Sessions.GROUP_ID + " , " + Table.Sessions.IS_NATIVE + " , " + Table.Sessions.RECURRENCE_RULE + " , " + Table.Sessions.TITLE + " , " + Table.Sessions.SESSION_TYPE + " " + " from " + Table.Sessions.TABLE_NAME + " where " + Table.DELETED + " = 0 " + " and ( " + Table.Sessions.START_DATE + " = datetime(\'" + date + "\') " + " OR " + Table.Sessions.RECURRENCE_RULE + " IS NOT NULL " + " OR " + Table.Sessions.RECURRENCE_RULE + " != '' ) "; Log.d("query is ", query); assert sqlDB != null; Cursor cursor = sqlDB.rawQuery(query, null); Log.d("Calendar", "Month Count = " + cursor.getCount()); LinkedHashMap<String, Object> row; while (cursor.moveToNext()) { if (cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)) == null || cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)).equals("")) { row = new LinkedHashMap<String, Object>(); long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID)); int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE)); rowData = getImageName(groupSessionId + "", session_type); row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID))); row.put("name", Utils.dateConversionForRow( cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE))) + " " + Utils.timeFormatAMPM( cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME)))); row.put("rowId", groupSessionId); row.put("type", session_type); if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) { row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE))); row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus)); Log.d("Calendar", "native events"); } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) { row.put("photo", rowData.getImageName()); row.put("secondLabel", rowData.getPersonName()); row.put("thirdLabel", status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]); Log.d("Calendar", "app events"); } Log.d("Calendar", (String) row.get("secondLabel")); mapArrayList.add(row); } else { String rule = cursor.getString(cursor.getColumnIndex(Table.Sessions.RECURRENCE_RULE)); RecurrenceRule recRule = new RecurrenceRule(rule); RecurrenceRule.Freq freq = recRule.getFreq(); Date d = new SimpleDateFormat("dd MMM yyyy").parse(Utils.formatConversionSQLite( cursor.getString(cursor.getColumnIndex(Table.Sessions.START_DATE)))); switch (freq) { case MONTHLY: d.setMonth(stDate.getMonth()); case YEARLY: d.setYear(stDate.getYear()); } if (freq == RecurrenceRule.Freq.MONTHLY || freq == RecurrenceRule.Freq.YEARLY) { if (!(d.after(stDate) && d.before(edDate))) continue; } ArrayList<Calendar> dates; dates = CalendarMonthViewFragment.ruleOccurONDate(rule, stDate, edDate); Log.e("RecurRule", "size = " + dates.size()); if (dates.size() > 0) { row = new LinkedHashMap<String, Object>(); if (freq == RecurrenceRule.Freq.DAILY || freq == RecurrenceRule.Freq.WEEKLY) { if (d.after(dates.get(0).getTime())) continue; } long groupSessionId = cursor.getInt(cursor.getColumnIndex(Table.Sessions.GROUP_ID)); int session_type = cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_TYPE)); rowData = getImageName(groupSessionId + "", session_type); row.put("_id", cursor.getString(cursor.getColumnIndex(Table.Sessions.ID))); row.put("name", Utils.formatConversionDateOnly(stDate) + " " + Utils.timeFormatAMPM( cursor.getString(cursor.getColumnIndex(Table.Sessions.START_TIME)))); row.put("rowId", groupSessionId); row.put("type", session_type); if (cursor.getInt(cursor.getColumnIndex(Table.Sessions.IS_NATIVE)) == 1) { row.put("secondLabel", cursor.getString(cursor.getColumnIndex(Table.Sessions.TITLE))); row.put("thirdLabel", getActivity().getString(R.string.lblNativeStatus)); Log.d("Calendar", "native events"); } else if (rowData.getImageName() != null && rowData.getImageName().length() > 0) { row.put("photo", rowData.getImageName()); row.put("secondLabel", rowData.getPersonName()); row.put("thirdLabel", status[cursor.getInt(cursor.getColumnIndex(Table.Sessions.SESSION_STATUS))]); Log.d("Calendar", "app events"); } Log.d("Calendar", (String) row.get("secondLabel")); mapArrayList.add(row); } } } cursor.close(); } catch (Exception e) { e.printStackTrace(); } CustomAsyncTaskListAdapter adapter = new CustomAsyncTaskListAdapter(getActivity(), R.layout.calendar_day_view_session_row, R.id.ivRowImage, R.id.tvFirstName, R.id.tvSecondLabel, R.id.tvThirdLabel, mapArrayList); sessionList.setAdapter(adapter); }
From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java
private List<Encounter> randomizeEncounterDates(List<Obs> patientObsList) { Integer flag = 0;/*from ww w . jav a 2s.co m*/ List<Date> randomizedEncounterDateList = new ArrayList<Date>(); List<Encounter> en = new ArrayList<Encounter>(); for (Obs o : patientObsList) { en.add(o.getEncounter()); } int year, month, date; try { for (int i = 0; i < patientObsList.size(); i++) { Date d = new Date(); if (flag == 0) { d.setDate(en.get(0).getEncounterDatetime().getDate()); d.setMonth(en.get(0).getEncounterDatetime().getMonth()); d.setYear(en.get(0).getEncounterDatetime().getYear()); flag = 1; } else { d.setDate(en.get(i - 1).getEncounterDatetime().getDate()); d.setMonth(en.get(i - 1).getEncounterDatetime().getMonth()); d.setYear(en.get(i - 1).getEncounterDatetime().getYear()); } year = d.getYear() + 1900; month = d.getMonth(); date = d.getDate(); //Randomize year = randBetween(year + 1, year + 2); month = randBetween(month, 12); date = randBetween(date, 30); //Set date d.setYear(year - 1900); d.setMonth(month); d.setDate(date); en.get(i).setEncounterDatetime(d); randomizedEncounterDateList.add(d); } } catch (APIException e) { log.error("Exception in randomizing encounter dates", e); } return en; }
From source file:org.dspace.rest.ItemsResource.java
/** * Create bitstream in item.//w w w . j a v a2 s . c o m * * @param itemId Id of item in DSpace. * @param inputStream Data of bitstream in inputStream. * @param headers If you want to access to item under logged user into context. * In headers must be set header "rest-dspace-token" with passed * token from login method. * @return Returns bitstream with status code OK(200). If id of item is * invalid , it returns status code NOT_FOUND(404). If user is not * allowed to write to item, UNAUTHORIZED(401). * @throws WebApplicationException It is thrown by these exceptions: SQLException, when was * problem with reading/writing from/to database. * AuthorizeException, when was problem with authorization to * item and add bitstream to item. IOException, when was problem * with creating file or reading from inpustream. * ContextException. When was problem with creating context of * DSpace. */ // TODO Add option to add bitstream by URI.(for very big files) @POST @Path("/{item_id}/bitstreams") @ApiOperation(value = "Create a bitstream in an item by using the internal DSpace item identifier.", response = org.dspace.rest.common.Bitstream.class) public Bitstream addItemBitstream( @ApiParam(value = "The identifier of the item.", required = true) @PathParam("item_id") Integer itemId, @ApiParam(value = "InputStream object", required = true) InputStream inputStream, @ApiParam(value = "The name of the bitstream.", required = true) @QueryParam("name") String name, @ApiParam(value = "The description of the bitstream.", required = false) @QueryParam("description") String description, @ApiParam(value = "The group id of the policy group.", required = false) @QueryParam("groupId") Integer groupId, @ApiParam(value = "The year of the policy start date.", required = false) @QueryParam("year") Integer year, @ApiParam(value = "The month of the policy start date.", required = false) @QueryParam("month") Integer month, @ApiParam(value = "The day of the policy start date.", required = false) @QueryParam("day") Integer day, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Adding bitstream to item(id=" + itemId + ")."); org.dspace.core.Context context = null; Bitstream bitstream = null; try { context = createContext(); org.dspace.content.Item dspaceItem = findItem(context, itemId, org.dspace.core.Constants.WRITE); writeStats(dspaceItem, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor, headers, request, context); // Is better to add bitstream to ORIGINAL bundle or to item own? log.trace("Creating bitstream in item."); Bundle bundle = null; org.dspace.content.Bitstream dspaceBitstream = null; Bundle[] bundles = dspaceItem.getBundles("ORIGINAL"); if (bundles != null && bundles.length != 0) { bundle = bundles[0]; // There should be only one bundle ORIGINAL. } if (bundle == null) { log.trace("Creating bundle in item."); dspaceBitstream = dspaceItem.createSingleBitstream(inputStream); } else { log.trace("Getting bundle from item."); dspaceBitstream = bundle.createBitstream(inputStream); } dspaceBitstream.setSource("DSpace Rest api"); // Set bitstream name and description if (name != null) { if (BitstreamResource.getMimeType(name) == null) { dspaceBitstream.setFormat(BitstreamFormat.findUnknown(context)); } else { dspaceBitstream.setFormat( BitstreamFormat.findByMIMEType(context, BitstreamResource.getMimeType(name))); } dspaceBitstream.setName(name); } if (description != null) { dspaceBitstream.setDescription(description); } dspaceBitstream.update(); // Create policy for bitstream if (groupId != null) { bundles = dspaceBitstream.getBundles(); for (Bundle dspaceBundle : bundles) { List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = dspaceBundle .getBitstreamPolicies(); // Remove default bitstream policies List<org.dspace.authorize.ResourcePolicy> policiesToRemove = new ArrayList<org.dspace.authorize.ResourcePolicy>(); for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) { if (policy.getResourceID() == dspaceBitstream.getID()) { policiesToRemove.add(policy); } } for (org.dspace.authorize.ResourcePolicy policy : policiesToRemove) { bitstreamsPolicies.remove(policy); } org.dspace.authorize.ResourcePolicy dspacePolicy = org.dspace.authorize.ResourcePolicy .create(context); dspacePolicy.setAction(org.dspace.core.Constants.READ); dspacePolicy.setGroup(Group.find(context, groupId)); dspacePolicy.setResourceID(dspaceBitstream.getID()); dspacePolicy.setResource(dspaceBitstream); dspacePolicy.setResourceType(org.dspace.core.Constants.BITSTREAM); if ((year != null) || (month != null) || (day != null)) { Date date = new Date(); if (year != null) { date.setYear(year - 1900); } if (month != null) { date.setMonth(month - 1); } if (day != null) { date.setDate(day); } date.setHours(0); date.setMinutes(0); date.setSeconds(0); dspacePolicy.setStartDate(date); } dspacePolicy.update(); dspaceBitstream.updateLastModified(); } } dspaceBitstream = org.dspace.content.Bitstream.find(context, dspaceBitstream.getID()); bitstream = new Bitstream(dspaceBitstream, ""); context.complete(); } catch (SQLException e) { processException("Could not create bitstream in item(id=" + itemId + "), SQLException. Message: " + e, context); } catch (AuthorizeException e) { processException( "Could not create bitstream in item(id=" + itemId + "), AuthorizeException. Message: " + e, context); } catch (IOException e) { processException("Could not create bitstream in item(id=" + itemId + "), IOException Message: " + e, context); } catch (ContextException e) { processException("Could not create bitstream in item(id=" + itemId + "), ContextException Message: " + e.getMessage(), context); } finally { processFinally(context); } log.info("Bitstream(id=" + bitstream.getId() + ") was successfully added into item(id=" + itemId + ")."); return bitstream; }
From source file:com.krawler.spring.crm.common.crmManagerDAOImpl.java
/** * To convert a date and time selected separately by user into corresponding combined datetime * from users selected timezone to systems timezone * * The first step is to keep track of the time difference in order to change the date if required. * Two time only objects dtold and dtcmp are created for this purpose. * * The date passed and the time passed that are in system timezone are formatted without * timezone and then parsed into the required timezone and then the time values are set * back to the date value sent./*w w w . ja v a 2s . co m*/ * **/ public Date converttz(String timeZoneDiff, Date dt, String time) { Calendar cal = Calendar.getInstance(); try { if (timeZoneDiff == null || timeZoneDiff.isEmpty()) { timeZoneDiff = "-7:00"; } String val; SimpleDateFormat sdf = new SimpleDateFormat("HHmm 'Hrs'"); Date dtold = sdf.parse("0000 Hrs"); if (!time.endsWith("Hrs")) { sdf = new SimpleDateFormat("hh:mm a"); dtold = sdf.parse("00:00 AM"); } SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm a"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm a"); sdf2.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed Date dt1 = sdf.parse(time); // Setting the passed time to the date object in system timezone sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed Date dtcmp = sdf.parse(time); // Parsing the time to timezone using passed values dt1.setMonth(dt.getMonth()); // Setting the date values sent to the system time only value dt1.setDate(dt.getDate()); dt1.setYear(dt.getYear()); dt1 = sdf2.parse(sdf1.format(dt1)); // Parsing datetime into required timezone dt.setHours(dt1.getHours()); // Setting the time values into the sent date dt.setMinutes(dt1.getMinutes()); dt.setSeconds(0); cal.setTime(dt); if (dtcmp.compareTo(dtold) < 0) { // Comparing for time value change cal.add(Calendar.DATE, -1); // in order to change the date accordingly } dtold.setDate(2); if (dtcmp.compareTo(dtold) > 0 || dtcmp.compareTo(dtold) == 0) { cal.add(Calendar.DATE, 1); } } catch (ParseException ex) { System.out.println(ex); } finally { return cal.getTime(); } }
From source file:com.progym.custom.fragments.WaterProgressYearlyLineFragment.java
public void setLineData3(final Date date, final boolean isLeftIn) { final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(), getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data), true);/*from w w w .j a va 2 s . c o m*/ ringProgressDialog.setCancelable(true); new Thread(new Runnable() { @Override public void run() { try { int yMaxAxisValue = 0; getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { rlRootGraphLayout.removeView(mChartView); } catch (Exception edsx) { edsx.printStackTrace(); } } }); DATE = date; // 31 - Amount of days in a month int daysInMonth = Utils.getDaysInMonth(date.getMonth(), Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY))); // set January as first month date.setMonth(0); date.setDate(1); int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // Creating an XYSeries for Consumed water XYSeries consumedSeries = new XYSeries("Consumed"); List<WaterConsumed> list; // int userShouldConsume = (int) DataBaseUtils.getWaterUserShouldConsumePerDay(); Date dt = date; // * // Adding data to Income and Expense Series for (int i = 0; i < x.length; i++) { // get all water records consumed per this month list = DataBaseUtils.getAllWaterConsumedInMonth( Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM)); // init "average" data int averageWaterConsumedOnYaxis = 0; for (int j = 0; j < list.size(); j++) { // calculate sum of all water consumed by user in a month averageWaterConsumedOnYaxis += list.get(j).volumeConsumed; } averageWaterConsumedOnYaxis = averageWaterConsumedOnYaxis / daysInMonth; consumedSeries.add(i, averageWaterConsumedOnYaxis); // normaSeries.add(i, userShouldConsume); dt = DateUtils.addMonths(dt, 1); yMaxAxisValue = Math.max(yMaxAxisValue, averageWaterConsumedOnYaxis); } // Creating a dataset to hold each series final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); // Adding Expense Series to dataset // dataset.addSeries(normaSeries); // Adding Income Series to the dataset dataset.addSeries(consumedSeries); // Creating XYSeriesRenderer to customize incomeSeries XYSeriesRenderer incomeRenderer = new XYSeriesRenderer(); incomeRenderer.setColor(Color.rgb(50, 255, 50)); incomeRenderer.setFillPoints(true); incomeRenderer.setLineWidth(2); incomeRenderer.setDisplayChartValues(true); /* * // Creating XYSeriesRenderer to customize expenseSeries * XYSeriesRenderer expenseRenderer = new XYSeriesRenderer(); * expenseRenderer.setColor(Color.rgb(80, 220, 80)); * expenseRenderer.setFillPoints(true); * expenseRenderer.setLineWidth(2); * expenseRenderer.setDisplayChartValues(true); */ // Creating a XYMultipleSeriesRenderer to customize the whole chart final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer(); multiRenderer.setXLabels(0); for (int i = 0; i < x.length; i++) { multiRenderer.addXTextLabel(i, ActivityWaterProgress.months_short[i]); } // Adding incomeRenderer and expenseRenderer to multipleRenderer // Note: The order of adding dataseries to dataset and renderers to multipleRenderer // should be same multiRenderer.setChartTitle(String.format("Water statistic for %s year", Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY))); multiRenderer.setXTitle("Months"); multiRenderer.setYTitle("Water volume (ml)"); multiRenderer.setAxesColor(Color.WHITE); multiRenderer.setShowLegend(true); multiRenderer.addSeriesRenderer(incomeRenderer); multiRenderer.setShowGrid(true); multiRenderer.setClickEnabled(true); // multiRenderer.addSeriesRenderer(expenseRenderer); multiRenderer.setXLabelsAngle(30); // multiRenderer.setBackgroundColor(Color.parseColor("#B3FFFFFF")); // multiRenderer.setApplyBackgroundColor(true); multiRenderer.setXLabelsColor(Color.WHITE); multiRenderer.setZoomButtonsVisible(false); // configure visible area multiRenderer.setXAxisMax(11.5); multiRenderer.setXAxisMin(-0.5); multiRenderer.setYAxisMax(yMaxAxisValue + (yMaxAxisValue / 5)); multiRenderer.setYAxisMin(-0.1); multiRenderer.setAxisTitleTextSize(15); multiRenderer.setBarSpacing(0.1); multiRenderer.setZoomEnabled(true); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mChartView = ChartFactory.getBarChartView(getActivity(), dataset, multiRenderer, Type.DEFAULT); rlRootGraphLayout.addView(mChartView, 0); if (isLeftIn) { rightIn.setDuration(1000); mChartView.startAnimation(rightIn); } else { leftIn.setDuration(1000); mChartView.startAnimation(leftIn); } } }); } catch (Exception e) { e.printStackTrace(); } ringProgressDialog.dismiss(); } }).start(); }
From source file:com.progym.custom.fragments.CalloriesProgressYearlyLineFragment.java
public void setYearProgressData(final Date date, final boolean isLeftIn) { final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(), getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data), true);/* w w w.ja v a2 s . co m*/ ringProgressDialog.setCancelable(true); new Thread(new Runnable() { @Override public void run() { try { int yMaxAxisValue = 0; getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { rlRootGraphLayout.removeView(viewChart); } catch (Exception edsx) { edsx.printStackTrace(); } } }); DATE = date; // Get amount of days in a month to find out average int daysInMonth = Utils.getDaysInMonth(date.getMonth(), Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY))); // set January as first month date.setMonth(0); date.setDate(1); int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); CategorySeries seriesCallories = new CategorySeries("Callories"); List<Ingridient> list; Date dt = date; // * for (int element : x) { list = DataBaseUtils.getAllFoodConsumedInMonth( Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM)); // init "average" data int totalCallories = 0; for (Ingridient ingridient : list) { totalCallories += ingridient.kkal; } // add value to series seriesCallories.add(totalCallories / daysInMonth); // calculate maximum Y axis values yMaxAxisValue = Math.max(yMaxAxisValue, totalCallories / daysInMonth); // increment month dt = DateUtils.addMonths(dt, 1); } int[] colors = new int[] { getActivity().getResources().getColor(R.color.purple) }; final XYMultipleSeriesRenderer renderer = buildBarRenderer(colors); setChartSettings(renderer, String.format("Callories statistic for %s year", Utils.getSpecificDateValue(DATE, "yyyy")), "Months", "Calories consumption", 0.7, 12.3, 0, yMaxAxisValue + 30, Color.GRAY, Color.LTGRAY); renderer.getSeriesRendererAt(0).setDisplayChartValues(true); renderer.getSeriesRendererAt(0).setChartValuesTextSize(15f); renderer.setXLabels(0); renderer.setClickEnabled(false); renderer.setZoomEnabled(false); renderer.setPanEnabled(false, false); renderer.setZoomButtonsVisible(false); renderer.setPanLimits(new double[] { 1, 11 }); renderer.setShowGrid(true); renderer.setShowLegend(true); renderer.setFitLegend(true); for (int i = 0; i < ActivityWaterProgress.months_short.length; i++) { renderer.addXTextLabel(i + 1, ActivityWaterProgress.months_short[i]); } dataset.addSeries(seriesCallories.toXYSeries()); getActivity().runOnUiThread(new Runnable() { @Override public void run() { viewChart = ChartFactory.getBarChartView(getActivity(), dataset, renderer, Type.DEFAULT); rlRootGraphLayout.addView(viewChart, 0); if (isLeftIn) { rightIn.setDuration(1000); viewChart.startAnimation(rightIn); } else { leftIn.setDuration(1000); viewChart.startAnimation(leftIn); } } }); } catch (Exception e) { } ringProgressDialog.dismiss(); } }).start(); }
From source file:com.progym.custom.fragments.FoodProgressYearlyLineFragment.java
public void setYearProgressData(final Date date, final boolean isLeftIn) { final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(), getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data), true);// www. jav a2s.c o m ringProgressDialog.setCancelable(true); new Thread(new Runnable() { @Override public void run() { try { int yMaxAxisValue = 0; getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { rlRootGraphLayout.removeView(viewChart); } catch (Exception edsx) { edsx.printStackTrace(); } } }); DATE = date; // Get amount of days in a month to find out average int daysInMonth = Utils.getDaysInMonth(date.getMonth(), Integer.valueOf(Utils.formatDate(date, DataBaseUtils.DATE_PATTERN_YYYY))); // set January as first month date.setMonth(0); date.setDate(1); int[] x = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; final XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); CategorySeries seriesProtein = new CategorySeries("Protein"); CategorySeries seriesFat = new CategorySeries("Fat"); CategorySeries seriesCarbs = new CategorySeries("Carbs"); List<Ingridient> list; Date dt = date; for (int element : x) { list = DataBaseUtils.getAllFoodConsumedInMonth( Utils.formatDate(dt, DataBaseUtils.DATE_PATTERN_YYYY_MM)); // init "average" data double totalProtein = 0, totalFat = 0, totalCarbs = 0, totalCallories = 0; for (Ingridient ingridient : list) { totalProtein += ingridient.protein; totalFat += ingridient.fat; totalCarbs += ingridient.carbohydrates; totalCallories += ingridient.kkal; } seriesProtein.add((double) Math.round(totalProtein * 100) / 100); seriesFat.add((double) Math.round(totalFat * 100) / 100); seriesCarbs.add((double) Math.round(totalCarbs * 100) / 100); // calculate maximum Y axis values yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalProtein); yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalFat); yMaxAxisValue = Math.max(yMaxAxisValue, (int) totalCarbs); // increment month dt = DateUtils.addMonths(dt, 1); } int[] colors = new int[] { getActivity().getResources().getColor(R.color.green), getActivity().getResources().getColor(R.color.orange), getActivity().getResources().getColor(R.color.purple) }; final XYMultipleSeriesRenderer renderer = buildBarRenderer(colors); setChartSettings(renderer, String.format("Protein/Carbohydrates/Fat statistic for %s year", Utils.getSpecificDateValue(DATE, "yyyy")), "Months", "Amount (g) ", 0.7, 12.3, 0, yMaxAxisValue + 30, Color.GRAY, Color.LTGRAY); renderer.getSeriesRendererAt(0).setDisplayChartValues(true); renderer.getSeriesRendererAt(1).setDisplayChartValues(true); renderer.getSeriesRendererAt(2).setDisplayChartValues(true); renderer.getSeriesRendererAt(0).setChartValuesTextSize(15f); renderer.getSeriesRendererAt(1).setChartValuesTextSize(15f); renderer.getSeriesRendererAt(2).setChartValuesTextSize(15f); // renderer.getSeriesRendererAt(0).setChartValuesTextAlign(Align.CENTER); // renderer.getSeriesRendererAt(1).setChartValuesTextAlign(Align.LEFT); // renderer.getSeriesRendererAt(2).setChartValuesTextAlign(Align.RIGHT); renderer.setXLabels(0); // renderer.setYLabels(10); // renderer.setXLabelsAlign(Align.LEFT); // renderer.setYLabelsAlign(Align.LEFT); // renderer.setPanEnabled(true, false); renderer.setClickEnabled(false); renderer.setZoomEnabled(false); renderer.setPanEnabled(false, false); renderer.setZoomButtonsVisible(false); renderer.setPanLimits(new double[] { 1, 11 }); // renderer.setZoomEnabled(false); // renderer.setZoomRate(1.1f); renderer.setShowGrid(true); renderer.setShowLegend(true); renderer.setFitLegend(true); for (int i = 0; i < ActivityWaterProgress.months_short.length; i++) { renderer.addXTextLabel(i + 1, ActivityWaterProgress.months_short[i]); } dataset.addSeries(seriesProtein.toXYSeries()); dataset.addSeries(seriesFat.toXYSeries()); dataset.addSeries(seriesCarbs.toXYSeries()); getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { viewChart = ChartFactory.getLineChartView(getActivity(), dataset, renderer/* , Type.STACKED */); rlRootGraphLayout.addView(viewChart, 0); if (isLeftIn) { rightIn.setDuration(1000); viewChart.startAnimation(rightIn); } else { leftIn.setDuration(1000); viewChart.startAnimation(leftIn); } } catch (Exception edsx) { edsx.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } ringProgressDialog.dismiss(); } }).start(); }
From source file:org.skt.runtime.html5apis.contacts.ContactAccessorSdk5.java
/** * Take the search criteria passed into the method and create a SQL WHERE clause. * @param fields the properties to search against * @param searchTerm the string to search for * @return an object containing the selection and selection args *//* w w w. j av a2s. c o m*/ private WhereOptions buildWhereClause(JSONArray fields, String searchTerm) { ArrayList<String> where = new ArrayList<String>(); ArrayList<String> whereArgs = new ArrayList<String>(); WhereOptions options = new WhereOptions(); /* * Special case where the user wants all fields returned */ if (isWildCardSearch(fields)) { // Get all contacts with all properties if ("%".equals(searchTerm)) { options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )"); options.setWhereArgs(new String[] { searchTerm }); return options; } else { // Get all contacts that match the filter but return all properties where.add("(" + dbMap.get("displayName") + " LIKE ? )"); whereArgs.add(searchTerm); where.add("(" + dbMap.get("name") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("nickname") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("phoneNumbers") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("emails") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); where.add( "(" + dbMap.get("addresses") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("ims") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("organizations") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("note") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE); where.add("(" + dbMap.get("urls") + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE); } } /* * Special case for when the user wants all the contacts but */ if ("%".equals(searchTerm)) { options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )"); options.setWhereArgs(new String[] { searchTerm }); return options; } String key; try { //Log.d(LOG_TAG, "How many fields do we have = " + fields.length()); for (int i = 0; i < fields.length(); i++) { key = fields.getString(i); if (key.equals("id")) { where.add("(" + dbMap.get(key) + " = ? )"); whereArgs.add(searchTerm.substring(1, searchTerm.length() - 1)); } else if (key.startsWith("displayName")) { where.add("(" + dbMap.get(key) + " LIKE ? )"); whereArgs.add(searchTerm); } else if (key.startsWith("name")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE); } else if (key.startsWith("nickname")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE); } else if (key.startsWith("phoneNumbers")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); } else if (key.startsWith("emails")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); } else if (key.startsWith("addresses")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE); } else if (key.startsWith("ims")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE); } else if (key.startsWith("organizations")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE); } else if (key.startsWith("birthday")) { try { SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); Date searchDate = format.parse(searchTerm.substring(1, searchTerm.length() - 1)); // Have to subtract one from the month as JavaScript's January is 01 // while Java's January is 00. searchDate.setMonth(searchDate.getMonth() - 1); SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); where.add("(" + dbMap.get(key) + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(newFormat.format(searchDate)); whereArgs.add(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE); } catch (ParseException e) { Log.d(LOG_TAG, "Bad romance format"); } } else if (key.startsWith("note")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE); } else if (key.startsWith("urls")) { where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )"); whereArgs.add(searchTerm); whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE); } } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } // Creating the where string StringBuffer selection = new StringBuffer(); for (int i = 0; i < where.size(); i++) { selection.append(where.get(i)); if (i != (where.size() - 1)) { selection.append(" OR "); } } options.setWhere(selection.toString()); // Creating the where args array String[] selectionArgs = new String[whereArgs.size()]; for (int i = 0; i < whereArgs.size(); i++) { selectionArgs[i] = whereArgs.get(i); } options.setWhereArgs(selectionArgs); return options; }
From source file:com.zoho.creator.jframework.XMLParser.java
private static void parseAndSetCalendarRecords(ZCView zcView, Node calendarNode) { zcView.setGrouped(true);/* w w w.ja v a 2s .co m*/ NodeList eventsList = calendarNode.getChildNodes(); int year = zcView.getRecordsMonthYear().getTwo() - 1900; int month = zcView.getRecordsMonthYear().getOne(); GregorianCalendar cureentmnthcalendar = new GregorianCalendar(); Date currentDate = new Date(); for (int i = 0; i < eventsList.getLength(); i++) { Node eventNode = eventsList.item(i); NamedNodeMap eventAttrMap = eventNode.getAttributes(); long recordid = Long.parseLong(eventAttrMap.getNamedItem("id").getNodeValue()); //No I18N String title = getChildNodeValue(eventNode, "title"); //eventAttrMap.getNamedItem("title").getNodeValue(); //No I18N boolean isAllDay = Boolean.parseBoolean(eventAttrMap.getNamedItem("allDay").getNodeValue()); //No I18N // 07/31/2013 08:00:00 String dateFormat = "MM/dd/yyyy HH:mm:ss"; //No I18N if (isAllDay) { dateFormat = "MM/dd/yyyy"; //No I18N } Date startTime = getDateValue(eventAttrMap.getNamedItem("start").getNodeValue(), dateFormat); //No I18N ZCRecord record = zcView.getRecord(recordid); record.setEventTitle(title); if (isAllDay) { zcView.setIsAllDay(isAllDay); Node endNode = eventAttrMap.getNamedItem("end");//No I18N Date endTime = null; if (endNode != null) { endTime = getDateValue(endNode.getNodeValue(), dateFormat); } int startDay = -1; if (startTime != null) { startDay = startTime.getDate(); } int endDay = -1; if (endTime != null) { endDay = endTime.getDate(); } if (endDay != -1) { currentDate.setDate(1); currentDate.setMonth(month); currentDate.setYear(year); currentDate.setMinutes(0); currentDate.setHours(0); currentDate.setSeconds(0); cureentmnthcalendar.setTime(currentDate); cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, -6); currentDate = cureentmnthcalendar.getTime(); for (int j = 0; j < 42; j++) { if ((currentDate.getDate() == startTime.getDate() && currentDate.getMonth() == startTime.getMonth() && currentDate.getYear() == startTime.getYear()) || (currentDate.after(startTime) && currentDate.before(endTime)) || (currentDate.getDate() == endTime.getDate() && currentDate.getMonth() == endTime.getMonth() && currentDate.getYear() == endTime.getYear())) { zcView.setEvent(record, currentDate); } cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, 1); currentDate = cureentmnthcalendar.getTime(); } //Collections.sort(eventRecords); } record.setEventDate(startTime); } else { // 07/31/2013 08:00:00 Date endTime = getDateValue(eventAttrMap.getNamedItem("end").getNodeValue(), dateFormat); //No I18N record.setStartTime(startTime); record.setEndTime(endTime); Calendar startCalendar = new GregorianCalendar(); startCalendar.setTime(startTime); startCalendar.set(Calendar.HOUR_OF_DAY, 0); startCalendar.set(Calendar.MINUTE, 0); startCalendar.set(Calendar.SECOND, 0); startCalendar.set(Calendar.MILLISECOND, 0); Calendar endCalendar = new GregorianCalendar(); endCalendar.setTime(endTime); endCalendar.set(Calendar.HOUR_OF_DAY, 0); endCalendar.set(Calendar.MINUTE, 0); endCalendar.set(Calendar.SECOND, 0); endCalendar.set(Calendar.MILLISECOND, 0); Date eventDate = new Date(startCalendar.getTimeInMillis()); zcView.setEvent(record, eventDate); while ((startCalendar.get(Calendar.YEAR) != endCalendar.get(Calendar.YEAR)) || (startCalendar.get(Calendar.MONTH) != endCalendar.get(Calendar.MONTH)) || (startCalendar.get(Calendar.DATE) != endCalendar.get(Calendar.DATE))) { startCalendar.add(Calendar.DATE, 1); eventDate = new Date(startCalendar.getTimeInMillis()); zcView.setEvent(record, eventDate); } } } List<ZCGroup> zcGroups = zcView.getGroups(); HashMap<Date, List<ZCRecord>> eventsMap = zcView.getEventRecordsMap(); SortedSet<Date> keys = new TreeSet<Date>(eventsMap.keySet()); for (Date eventDate : keys) { List<ZCRecord> eventRecords = eventsMap.get(eventDate); List<String> groupHeaderValues = new ArrayList<String>(); SimpleDateFormat dateFormat = new SimpleDateFormat(zcView.getDateFormat()); //No I18N groupHeaderValues.add(dateFormat.format(eventDate)); ZCGroup zcGroup = new ZCGroup(groupHeaderValues); zcGroups.add(zcGroup); for (int i = 0; i < eventRecords.size(); i++) { ZCRecord eventRecord = eventRecords.get(i); zcGroup.addRecord(eventRecord); } } zcView.sortRecordsForCalendar(); }