Foros aprenderaprogramar.com
Aprender a programar => C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más => Mensaje iniciado por: Tino en 29 de Julio 2014, 19:48
-
Hola.
Soy muy nuevo en esto y creo que no controlo demasiadas cosas.
Quiero elaborar un metodo en java para que me devuelva los dias de trabajo. Es decir
desde el 1 de enero de 2014 por ejemplo hasta el 31 de diciembre de 2050 por ejemplo
La cadencia de trabajo seria en ciclos de ocho dias: trabajo, libre,trabajo,trabajo, libre, libre, libre, libre.
Por lo menos me gustaria que alguien me orientara como realizarlo. Estoy bloqueado.
Gracias.
-
Hola, no parece demasiado complicado, aunque obviamente hay que pensarlo bien. Si te fijas en la idea que planteas y la cadencia es regular (es decir, de cada 8 días, el primero es trabajo, el segundo libre, el tercero trabajo, etc.) tendrías una repetición de un ciclo cada 8 unidades. Esto no es difícil de modelar usando el operador módulo (%).
En principio, podrías obtener un valor numérico que te indique el día de que se trata. Supongamos que el 1 de enero de 2014 tiene el equivalente numérico 204788.
Ahora se podría plantear que el método reciba la fecha, obtenga su equivalente numérico, y le reste 204787. De este modo, al 1 de enero de 2014 le correspondería el valor 1.
Seguidamente hacemos el módulo de 1 % 8 = 7
Para cada valor tendríamos:
si valor % 8 = 7 entonces el tipo de día es trabajo
si valor % 8 = 6 entonces el tipo de día es libre
si valor % 8 = 5 entonces el tipo de día es trabajo
si valor % 8 = 4 entonces el tipo de día es trabajo
si valor % 8 = 3 entonces el tipo de día es libre
si valor % 8 = 2 entonces el tipo de día es libre
si valor % 8 = 1 entonces el tipo de día es libre
si valor % 8 = 0 entonces el tipo de día es libre
Seguramente también se puede plantear de otras maneras, pero esta en principio es la que me ha parecido más simple. Saludos.
-
Muchas gracias por tu rapida respuesta.
Como puedo o como se asigna el valor a cada fecha.
Porque lo que realmente lo que pretendo es que me devuelva los dias que trabajo por ejemplo para luego utilizarlos en un calendario ( que ya tengo) y colocar algun evento o cambio de color etc..
Gracias
-
Tienes que tener en cuenta la versión de java con la que estés trabajando, Si usas Java 8 o superior, se recomienda el uso de las clases incluidas dentro del paquete java.time (http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html), en versiones anteriores el trabajo con fechas puede resultar distinto. Según la versión que vayas a emplear tendrás que estudiar qué clases y métodos pueden resultarte útiles. Saludos.
-
No se si me he explicado bien. Lo que pretendo es crear un método que con esa cadencia de trabajo y empezando por ejemplo el 1 de enero, me devuelva : 1 de enero, 3 de enero, 4 de enero, 9 de enero, 11 de enero,..... Hasta la fecha deseada.
Gracias
-
Ooops! Pues la verdad es que no lo había entendido así, pero tampoco cambia demasiado, es decir, que se puede seguir usando el planteamiento de las cadencias o repeticiones.
Supongamos que quieres tener un ArrayList de Dates con los días de trabajo del año 2014. Supongamos que el 1 de enero de 2014 tiene el equivalente numérico 204788 y lo hacemos equivalente a día 1.
1-trabajo, libre,3-trabajo,4-trabajo, libre, libre, libre, libre.
9-trabajo, libre,11-trabajo,12-trabajo, libre, libre, libre, libre.
17-trabajo, libre,19-trabajo,20-trabajo, libre, libre, libre, libre.
etc. etc.
Lo que encontramos aquí es que partiendo del día 1 todos los días que resultan de sumar 1+8=9, 1+8+8=17, 1+8+8+8=25, etc. son días de trabajo.
Partiendo del día 3 todos los días que resultan de sumar 3+8 = 11, 3+8+8 = 19, 3+8+8+8=27 etc. son días de trabajo.
Partiendo del día 4 todos los días que resultan de sumar 4+8=12, 4+8+8=20, etc. son días de trabajo.
Para crear el ArrayList podríamos partir del día 1 y añadir todas las fechas de la sucesión. Luego partir del día 3 y añadir todas las fechas de la sucesión. Luego partir del día 4 y añadir todas las fechas de la sucesión... de esa forma tendrías todas las fechas almacenadas. Hablamos de números como fechas, de este modo puedes usar el número o la fecha (convertir en un sentido u otro según prefieras, cuando quieras).
Aunque pensándolo por otro lado, no parece que tenga demasiado sentido almacenar las fechas, parecería más lógico hacer una gestión dinámica, es decir, los calendarios universales que te permiten ver el calendario de una semana de por ejemplo el año 2584 no almacenan la información, sino que la generan dinámicamente con el algoritmo adecuado cuando se les pide que muestren algo concreto. Si no fuera así, la cantidad de información sería descomunal y la eficiencia muy baja...
Saludos
-
Hola de nuevo. Desde la ultima notificacion no he podido dedicar nada de tiempo a trabajar en ello, he estado un poco pachucho. Pero ahora sigo con las mismas dudas. Tratare de concretar un poco mas. Empezamos:
Trato de hacer una aplicación para mi trabajo. Lo hago a turnos y con una cadencia de 8 dias:
TLTTLLLL donde T es trabajo y L libre.
He “confeccionado” un calendario (uno ya existente) y lo estoy modificando a mis necesidades.
Quiero empezar el 1 de enero de 2015.
Los días de trabajo quiero modificar el color del dia o de la celda(eso lo se realizar).
Se que tengo que crear un método donde mediante “ % 8 “ me devolverá un nº y si es el 1,3,4
corresponde a trabajo y el resto no. Pero como puedo operar con las fechas,
porque tiene que corresponder con las que aparezca en la vista del calendario.
Es decir si en el calendario me aparece el mes de febrero del 2015 aparezcan en distinto color los días de trabajo.
En el Adapter del calendario define un” private final List<String> list;” que es donde va a guardar los días. Y mediante esto:
if (i== getCurrentDayOfMonth()){
list.add(String.valueOf(i) + "-BLUE"+ "-"+ getMonthAsString(currentMonth)+ "-" +yy);
guarda el dia del mes.
Yo trato de aprovechar esto para con lo que me devualva el método almacenar los días de trabajo.
No se si esa variable i es la que tengo que pasar al método, como poder operar con ella y
entiendo que si retorna 1,3,4 sea true para que me lo guarde en “list”.
Y el método lo puedo colocar en una clase diferente o tiene que situarse en la clase del Adaper.
Luego quiero trabajar con el para colocar varios turnos mediante las preferencias.
No se si esta mas claro o si es mucho lo que pido, pero de antemano muchas gracias por leer este mensaje.
Gracias y un saludo.
-
Hola, pega el código de las clases que participan para poder compilarlo y revisarlo. Para ello usa el botón # que aparece en el editor del foro (pegar el código entre las etiquetas [cod] ... [/cod]). Si el código es demasiado largo o intervienen demasiadas clases puedes ponerlo como archivo adjuntos pulsando en "Opciones adicionales" en la parte inferior del editor del foro
Saludos!
-
Hola de nuevo. Te envio la clase Calendarview que es la de vista del calendario. Dentro esta la Clase GridCellAdapter donde esta el adaptador. Te envio la app del calendario. No me deja pegar todo lo que yo he desarrollado. Si quieres te lo envio por otro conducto.
Gracias de antemano por tu dedicacion. Un saludo.
package com.example4.mcalendar;
import java.nio.channels.GatheringByteChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
@TargetApi(3)
public class Calendarview extends Activity implements OnClickListener {
private static final String tag = "Calendarview";
private TextView currentMonth;
private Button selectedDayMonthYearButton, permisos, cambios,listacambios, listapermisos;
private ImageView prevMonth;
private ImageView nextMonth;
private GridView calendarView;
private GridCellAdapter adapter;
private Calendar calendar;
@SuppressLint("NewApi")
private int month, year;
@SuppressWarnings("unused")
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";
Animation animacion, animaalejar, animacercar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendarview);
calendar = Calendar.getInstance(Locale.getDefault());
month = calendar.get(Calendar.MONTH)+1;
year = calendar.get(Calendar.YEAR);
Log.d(tag, "Calendar Instance: =" + "month" + " " +"year: " + year );
selectedDayMonthYearButton = (Button) this.findViewById(R.id.selectedDayMonthYear);
// animacion del texto
animacion = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.parpadear);
selectedDayMonthYearButton.startAnimation(animacion);
animaalejar = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.alejar);
animacercar = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.acercar);
permisos= (Button)findViewById(R.id.settings);
permisos.setOnClickListener(this);
cambios = (Button)findViewById(R.id.addEvent);
cambios.setOnClickListener(this);
selectedDayMonthYearButton.setOnClickListener(this);
listacambios =(Button)findViewById(R.id.listaparacambios);
listacambios.setOnClickListener(this);
listapermisos =(Button)findViewById(R.id.listaparapermisos);
listapermisos.setOnClickListener(this);
prevMonth = (ImageView)this.findViewById(R.id.prevmonth);
prevMonth.setOnClickListener(this);
currentMonth = (TextView)this.findViewById(R.id.currentmonth);
currentMonth.setText(DateFormat.format(dateTemplate, calendar.getTime()));
nextMonth = (ImageView)this.findViewById(R.id.nextmonth);
nextMonth.setOnClickListener(this);
calendarView = (GridView)this.findViewById(R.id.calendar);
adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell,month,year);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
private void setGridCellAdapterToDate (int month, int year){
adapter =new GridCellAdapter(getApplicationContext(),R.id.calendar_day_gridcell, month, year);
calendar.set(year, month- 1, calendar.get(Calendar.DAY_OF_MONTH));
currentMonth.setText(DateFormat.format(dateTemplate, calendar.getTime()));
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nombre = selectedDayMonthYearButton.getText().toString();
if(v== prevMonth){
if(month <= 1){
month = 12;
year --;
}else {
month--;
}
Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month:" + month + "year: " +year);
setGridCellAdapterToDate(month, year);
}
if ( v==nextMonth){
if (month> 11){
month = 1;
year++;
}else{
month++;
}
Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month" + month + "year: " + year);
setGridCellAdapterToDate(month, year);
}
if(v==cambios){
Intent i = new Intent(this, CambioServicio.class);
Bundle cambio = new Bundle();
cambio.putString("NOMBRE", nombre);
i.putExtras(cambio);
startActivity(i);
}
if(v==permisos){
Intent i = new Intent(this, DiaPermiso.class);
Bundle cambio = new Bundle();
cambio.putString("NOMBRE", nombre);
i.putExtras(cambio);
startActivity(i);
}
if(v==listacambios){
Intent i = new Intent(this, ListaCambios.class);
startActivity(i);
listacambios.startAnimation(animaalejar);
listacambios.startAnimation(animacercar);
}
if(v==listapermisos){
Intent i = new Intent(this,ListaPermisos.class);
startActivity(i);
listapermisos.startAnimation(animaalejar);
listapermisos.startAnimation(animacercar);
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
Log.d(tag, "Destroying View...");
super.onDestroy();
}
public class GridCellAdapter extends BaseAdapter implements OnClickListener{
private static final String tag = "GridCellAdapter";
private final Context context;
private final List<String> list;
private static final int DAY_OFFSET = 1;
private final String[]weekdays = new String[] {"sun","Mon", "Tue", "Wed", "Thu","Fri","Sat" };
//private final String[]months = {"January","February","March","April","May","June","July",
//"August","Septembre","October","November","December"};
private final String[]months= {"Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto",
"Septiembre","Octubre","Noviembre","Dicienbre"};
private final int[] daysOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
private int daysInMonth;
private int currentDayOfMonth;
private int currentWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
public GridCellAdapter(Context context,int textViewResourceId,int month, int year){
super();
this.context = context;
this.list = new ArrayList<String>();
Log.d(tag, "==< Passed in Date FOR Month: " +month + " " + "year" + year);
Calendar calendar = Calendar.getInstance();
setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
Log.d(tag, "New Calendar: =" + calendar.getTime().toString());
Log.d(tag, "CurrentDayOfWeek : " + getCurrentWeekDay());
Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());
printMonth(month, year);
eventsPerMonthMap =findNumberOfEventsPerMonth(year,month);
}
private String getMonthAsString(int i){
return months[i];
}
private String getWeekDayAsString( int i){
return weekdays[i];
}
private int getNumberOfDaysOfMonth(int i){
return daysOfMonth[i];
}
public int getCount() {
return list.size();
}
public String getItem(int position) {
return list.get(position);
}
private void printMonth(int mm,int yy){
Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy" + yy);
int trailingSpaces = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = mm-1;
String currentMonthName = getMonthAsString(currentMonth);
daysInMonth = getNumberOfDaysOfMonth(currentMonth);
Log.d(tag, "Current Month: " + " " + currentMonthName + "having" + daysInMonth + "days");
//modificado 1 por 0
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);
Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());
if (currentMonth ==11){
prevMonth = currentMonth - 1;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 0;
prevYear = yy;
nextYear = yy +1;
Log.d(tag, "*->PrevYear: " + prevYear + "PrevMonth:" + prevMonth +
"nextmonth: " + nextMonth + "NextYear: "+ nextYear);
} else if (currentMonth ==0){
prevMonth = 11;
prevYear = yy-1;
nextYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 1;
Log.d(tag, "**-->PrevYear: " + prevYear + "PrevMonth: " + prevMonth +
"nextMonth: " + nextMonth+ "NextYear: " + nextYear);
}else{
prevMonth = currentMonth -1;
nextMonth = currentMonth +1;
nextYear =yy;
prevYear =yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
Log.d(tag, "***--->PrevYear:" + prevYear+ "PrevMonth: " +prevMonth+
"NextMont: " +nextMonth + "NextYear: " +nextYear);
}
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK)-1;
trailingSpaces = currentWeekDay;
Log.d(tag, "Week Day: " + currentWeekDay + "is"+getWeekDayAsString(currentWeekDay));
Log.d(tag, "No. Trailing space to Add:" + trailingSpaces);
Log.d(tag, "No. of Days in Previous Month:" +daysInPrevMonth);
if (cal.isLeapYear(cal.get(Calendar.YEAR)))
if (mm==2)
++daysInMonth;
else if (mm==3)
++daysInPrevMonth;
for (int i =0; i<trailingSpaces;i++){
Log.d(tag, "PREV MONTH:=" + prevMonth+ "=> "+ getMonthAsString(prevMonth)+ " "+
String.valueOf((daysInPrevMonth- trailingSpaces+ DAY_OFFSET)+i));
list.add(String.valueOf((daysInPrevMonth- trailingSpaces + DAY_OFFSET)+i)+ "-GREY"+
"-" + getMonthAsString(prevMonth)+ "-" + prevYear);
}
for (int i = 1; i<=daysInMonth; i++){
Log.d(currentMonthName, String.valueOf(i)+ " " + getMonthAsString(currentMonth)+
" "+ yy);
if (i== getCurrentDayOfMonth()){
list.add(String.valueOf(i) + "-BLUE"+ "-"+ getMonthAsString(currentMonth)+ "-" +yy);
}else{
list.add(String.valueOf(i)+ "-WHITE"+ "-"+ getMonthAsString(currentMonth)+ "-"+ yy);
}
}
for (int i=0; i<list.size()% 7;i++){
Log.d(tag, "NEXT MONTH:=" + getMonthAsString(nextMonth));
list.add(String.valueOf(i+ 1)+ "-GREY"+ "-" + getMonthAsString(nextMonth)+
"-"+ nextYear );
}
}
private HashMap<String, Integer> findNumberOfEventsPerMonth (int year,int month){
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (row ==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.screen_gricell, parent, false);
}
gridcell = (Button)row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(this);
Log.d(tag, "Current Day"+ getCurrentDayOfMonth());
String[]day_color = list.get(position).split("-");
String theday = day_color [0];
String themonth = day_color[2];
String theyear = day_color[3];
if( !eventsPerMonthMap.isEmpty() && (eventsPerMonthMap != null)){
if (eventsPerMonthMap.containsKey(theyear)){
num_events_per_day = (TextView)row.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer)eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
gridcell.setText(theday);
gridcell.setTag(theday+ "-"+ themonth+ "-" + theyear);
Log.d(tag, "Setting GridCell" + theday+ "-"+ themonth+ "-" +theyear);
if (day_color[1].equals("GREY")){
gridcell.setTextColor(getResources().getColor(R.color.lightgray));
}
if (day_color[1].equals("WHITE")){
gridcell.setTextColor(getResources().getColor(R.color.lightgray02));
}
if (day_color[1].equals("BLUE")){
gridcell.setTextColor(getResources().getColor(R.color.orrange));
//gridcell.setBackgroundColor(getResources().getColor(R.color.blue));
}
return row;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
String date_month_year= (String)view.getTag();
selectedDayMonthYearButton.setText(date_month_year);
Log.e("Selected date", date_month_year);
try{
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());
}catch (ParseException e){
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getCurrentDayOfMonth(){
return currentDayOfMonth;
}
private void setCurrentDayOfMonth(int currentDayOfMonth){
this.currentDayOfMonth = currentDayOfMonth;
}
public void setCurrentWeekDay (int currentWeekDay){
this.currentWeekDay = currentWeekDay;
}
public int getCurrentWeekDay(){
return currentWeekDay;
}
}
}
-
¿No puedes pegar lo que falte de código en otro post?
Por lo que se ve, la variable i representa el día del mes que se va a mostrar.
De la misma forma que en el código tienes
if (i== getCurrentDayOfMonth()){
list.add(String.valueOf(i) + "-BLUE"+ "-"+ getMonthAsString(currentMonth)+ "-" +yy);
Tendrías que añadir
if ( la fecha es dia de trabajo) {hacer esto } sino { hacer esto otro}
Piensa inicialmente simplemente en añadir un texto para que se muestre en el calendario, eso te dará la lógica y una vez tengas la lógica ya sólo te faltarían los detalles.
El contenido del calendario parece que lo almacena en la varialbe list.
La variable list es un ArrayList y la puedes recorrer y en ese recorrido añadir el texto que tú quieres:
for (int i=0; i<list.size(); i++){
if ( la fecha es dia de trabajo) {list.get(i) = list.get(i)+"(trabajo)" ); } sino {list.get(i) = list.get(i)+"(libre)" );}
}
Tienes que hacer pruebas hasta conseguir que se te muestre correctamente, luego ya introduces los colores como quieras...
Saludos
-
Hola de nuevo.
Te he mandado un adjunto con la app completa, aparece el calendario.
Si i es la variable del dia en curso podria crear un metodo para saber si trabajo o no.
Public int diadeTrabajo(int i){
:-[ int fechaInicio = 1 de enero de 2015; // como hago esto
int diasTranscurridos = i-fechadeInicio;
:-[ int trabajo =0 o null no lo se;
int trabajo = diasTrancurridos%8;
if( trabajo=1|| trabajo=3|| trabajo=4){
return true;
}else{
return false;
}
Luego en list se pondria
:-[ if (diasdeTrabajo()){
list.add(String.valueOf(i) + "-BLUE"+ "-"+ getMonthAsString(currentMonth)+ "-" +yy);
guardaria los dias que trabajo. Se supone que solamente las retun true o las false tambien.
Seria factible?. Mi problema es el manejo de i y el operar con fechas. No se cofeccinar el metodo.
Nuevamente gracias por perder el tiempo conmigo.
-
¿Dónde está el adjunto? Lo he buscado pero no lo veo.
La variable i es el día en curso, pero se refiere al día del mes. Por ejemplo, 3, 10 ó 27. Pero puedes recuperar la representación de la fecha completa, ya que tienes String.valueOf(i) + "-BLUE"+ "-"+ getMonthAsString(currentMonth)+ "-" +yy
Ahí está construyendo la fecha completa.
Para calcular la diferencia en días entre fechas tienes una explicación en las entregas CU00924C y CU00925C de este curso http://aprenderaprogramar.com/index.php?option=com_content&view=category&id=58&Itemid=180, aunque si estás usando java 8 tal y como se indica ahí <<Si trabajamos con Java 8 o superior, se recomienda el uso de las clases incluidas dentro del paquete java.time para el manejo de tiempos y fechas>>
-
Hola te envio el archibo adjunto adjunto.Es la vista del calendario.
Gracias de nuevo
-
Hola de nuevo. Adjunto un codigo de un metodo en el que trato de que me devuelva loa dias que trabajo.Bueno pues no soy capaz que me devuelva nada.Ayuda
public boolean diasdeTrabajo(){
Long diamess;
Long diferencia;
Long diadiferencia ;
long resultado = 0;
Calendar cal = GregorianCalendar.getInstance();
cal.set(2014,00,01);
Long seg = cal.getTimeInMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Calendar diames = GregorianCalendar.getInstance();
Date diasmes= null;
for(int i = 0;i<list.size();i++){
String is = Integer.toString(i);
try {
diasmes = format.parse(is);
diames.setTime(diasmes);
diamess = diames.getTimeInMillis();
diferencia = diamess - seg;
diadiferencia= (diferencia/1000*60*60*24);
resultado= diadiferencia % 8 ;
if(resultado == 1|| resultado == 3|| resultado == 4){
return true;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
cal :es la fecha de inicio que quiero que sea el 1 de enero del 2014.
trato de pasar todas las fechas almacenadas en "list" que son los dias del mes en formato "2014/02/23,2014/02/24,........."a cada una de ellas la resto la de cal y si el resto de dividirla por 8 es 1,3 o 4 me devuelva el dia correspondiente "True"?? y si no no devuelva nada.
Ayuda por favor que no se que hacer ya..
-
Hola, al intentar compilarlo aparece el error cannot find symbol - variable list, en la línea
for(int i = 0;i<list.size();i++){
pon un ejemplo de variable list para poder compilarlo y ver cuál es el fallo. Saludos!!!
-
public List<String> diasdeTrabajo(){
int GUARDIACUATRO1 =16070;
SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = GregorianCalendar.getInstance();
Date date = null;
for (int i=0;i <dias.size(); i++){
try {
date = formato.parse(list.get(i));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.setTime(date);
Long dia= cal.getTimeInMillis();
dia = dia/(1000*60*60*24);
dia =dia-GUARDIACUATRO1;
int seg2 = (int) (dia % 8);
if(seg2 == 1 || seg2 == 3|| seg2== 4){
diaTrabajo.add(dias.get(i)+ "-CURRO");
}else{
diaTrabajo.add(dias.get(i)+"-LIBRE");
}
}
return diaTrabajo;
}
Hola de nuevo. Estos dias he tenido mas tiempo y trato de avanzar en mi odisea.
Bien el codigo que he dejado es el de el metodo donde voy a saber si trabajo o no.
dias es un arraylist de los dias del mes: [14/10/01,14/10/02,14/10/03,......14/10/30]
si paso dias.size() me devuelve 30 y por ejemplo 31 en diciembre etc... todo bien.
Pero al pasar por el bucle for me develve el resultado deseado:14/10/01-LIBRE,14/10/02-CURRO...... Pero lo hace 45 veces es decir en el bucle repite el mes de noviembre 45 veces. Aparece para el mes de noviembre 30*45=1350 elementos.
Y claro esto es mucho para mi. Por favor que estoy haciendo mal.
Gracias
-
Referente al mensaje anterior en la linea date = formato.parse(list.get(i));
tiene que ser date = formato.parse(dias.get(i));
Perdon.
-
Hola ¿Cómo creas el array dias? Al intentar compilar me aparece el error cannot find symbol - variable dias :(
-
Hola. Creo l arraylist dias igual que se creo list pero con el año mes y dia del mes que aparece en pantalla. Cree un textview debajo del calendario para ver todas las salidas de mis pruebas.Te envio el codigo para que lo veas, pero lo que o entiendo ahora es lo del mensaje anterior.
Un saludo.package com.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
@TargetApi(3)
public class MyCalendarActivity extends Activity implements OnClickListener {
private static final String tag = "MyCalendarActivity";
private TextView currentMonth;
private Button selectedDayMonthYearButton;
private ImageView prevMonth;
private ImageView nextMonth;
private GridView calendarView;
private GridCellAdapter adapter;
private Calendar _calendar;
@SuppressLint("NewApi")
private int month, year;
@SuppressWarnings("unused")
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yy");
private static final String dateTemplate = "MMMM yyyy";
private TextView textoprueba;
long seg ;
// ArrayList<String> prueba = new ArrayList<String>();
private String tamaño;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_calendar_view);
_calendar = Calendar.getInstance(Locale.getDefault());
month = _calendar.get(Calendar.MONTH) + 1;
year = _calendar.get(Calendar.YEAR);
Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
+ year);
selectedDayMonthYearButton = (Button) this
.findViewById(R.id.selectedDayMonthYear);
selectedDayMonthYearButton.setText("Selected: ");
prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
prevMonth.setOnClickListener(this);
currentMonth = (TextView) this.findViewById(R.id.currentMonth);
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
nextMonth.setOnClickListener(this);
calendarView = (GridView) this.findViewById(R.id.calendar);
// Initialised
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
textoprueba = (TextView)this.findViewById(R.id.textoPruebas);
//textoprueba.setText("Estos son los dias de del mes "+pruebas());
}
/*public ArrayList<Integer> pruebas(){
prueba.add("202");
prueba.add("103");
prueba.add("225");
prueba.add("226");
prueba.add("302");
prueba.add("2");
ArrayList<Integer> result = new ArrayList<Integer>();
for(String stringValue :prueba) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(stringValue));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}*/
/**
*
* @param month
* @param year
*/
private void setGridCellAdapterToDate(int month, int year) {
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
@Override
public void onClick(View v) {
if (v == prevMonth) {
if (month <= 1) {
month = 12;
year--;
} else {
month--;
}
Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
if (v == nextMonth) {
if (month > 11) {
month = 1;
year++;
} else {
month++;
}
Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
}
@Override
public void onDestroy() {
Log.d(tag, "Destroying View ...");
super.onDestroy();
}
// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener {
private static final String tag = "GridCellAdapter";
private final Context _context;
private List<String> list;
private static final int DAY_OFFSET = 1;
private final String[] weekdays = new String[] { "Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat" };
//private final String[] months = { "January", "February", "March",
// "April", "May", "June", "July", "August", "September",
// "October", "November", "December" };
private final String[] months ={"00","01","02","03","04","05","06","07","08","09","10","11"};
private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
private int daysInMonth;
private int currentDayOfMonth;
private int currentWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
"dd-MM-yy"); //"dd-MMM-yyyy"
private List<String>dias;
private List<String>diaTrabajo;
// Days in Current Month
public GridCellAdapter(Context context, int textViewResourceId,
int month, int year) {
super();
this._context = context;
this.list = new ArrayList<String>();
Log.d(tag, "==> Passed in Date FOR Month: " + month + " "
+ "Year: " + year);
Calendar calendar = Calendar.getInstance();
setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());
this.dias = new ArrayList<String>();
this.diaTrabajo= new ArrayList<String>();
// Print Month
printMonth(month, year);
// Find Number of Events
eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
}
private String getMonthAsString(int i) {
return months[i];
}
private String getWeekDayAsString(int i) {
return weekdays[i];
}
private int getNumberOfDaysOfMonth(int i) {
return daysOfMonth[i];
}
public String getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
/**
* Prints Month
*
* @param mm
* @param yy
*/
private void printMonth(int mm, int yy) {
Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
int trailingSpaces = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = mm - 1;
String currentMonthName = getMonthAsString(currentMonth);
daysInMonth = getNumberOfDaysOfMonth(currentMonth);
Log.d(tag, "Current Month: " + " " + currentMonthName + " having "
+ daysInMonth + " days.");
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());
if (currentMonth == 11) {
prevMonth = currentMonth - 1;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 0;
prevYear = yy;
nextYear = yy + 1;
Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else if (currentMonth == 0) {
prevMonth = 11;
prevYear = yy - 1;
nextYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 1;
Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else {
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = yy;
prevYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
}
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
trailingSpaces = currentWeekDay;
Log.d(tag, "Week Day:" + currentWeekDay + " is "
+ getWeekDayAsString(currentWeekDay));
Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);
if (cal.isLeapYear(cal.get(Calendar.YEAR)))
if (mm == 2)
++daysInMonth;
else if (mm == 3)
++daysInPrevMonth;
// Trailing Month days
for (int i = 0; i < trailingSpaces; i++) {
Log.d(tag,
"PREV MONTH:= "
+ prevMonth
+ " => "
+ getMonthAsString(prevMonth)
+ " "
+ String.valueOf((daysInPrevMonth
- trailingSpaces + DAY_OFFSET)
+ i));
list.add(String
.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET)
+ i)
+ "-GREY"
+ "-"
+ getMonthAsString(prevMonth)
+ "-"
+ prevYear);
}
// Current Month Days
for (int i = 1; i <= daysInMonth; i++) {
Log.d(currentMonthName, String.valueOf(i) + " "
+ getMonthAsString(currentMonth) + " " + yy);
dias.add(yy+ "/"+getMonthAsString(currentMonth)+"/"+String.valueOf(i) );
if (i == getCurrentDayOfMonth()) {
list.add(String.valueOf(i) + "-BLUE" + "-"
+ getMonthAsString(currentMonth) + "-" + yy);
} else {
list.add(String.valueOf(i) + "-WHITE" + "-"
+ getMonthAsString(currentMonth) + "-" + yy);
}
}
// Leading Month days
for (int i = 0; i < list.size() % 7; i++) {
Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
list.add(String.valueOf(i + 1) + "-GREY" + "-"
+ getMonthAsString(nextMonth) + "-" + nextYear);
}
}
/**
* NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
* ALL entries from a SQLite database for that month. Iterate over the
* List of All entries, and get the dateCreated, which is converted into
* day.
*
* @param year
* @param month
* @return
*/
private HashMap<String, Integer> findNumberOfEventsPerMonth(int year,
int month) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.screen_gridcell, parent, false);
}
// Get a reference to the Day gridcell
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(this);
// ACCOUNT FOR SPACING
Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null)) {
if (eventsPerMonthMap.containsKey(theday)) {
num_events_per_day = (TextView) row
.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
// Set the Day GridCell
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"
+ theyear);
// textoprueba.setText("Estos son los dias de del mes "+list);
textoprueba.setText("Estos son los dias de del mes "+diasdeTrabajo());
if (day_color[1].equals("GREY")) {
gridcell.setTextColor(getResources()
.getColor(R.color.lightgray));
}
if (day_color[1].equals("WHITE")) {
gridcell.setTextColor(getResources().getColor(
R.color.lightgray02));
}
if (day_color[1].equals("BLUE")) {
gridcell.setTextColor(getResources().getColor(R.color.orrange));
}
return row;
}
@Override
public void onClick(View view) {
String date_month_year = (String) view.getTag();
selectedDayMonthYearButton.setText("Selected: " + date_month_year);
Log.e("Selected date", date_month_year);
try {
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
public List<String> diasdeTrabajo(){
int GUARDIACUATRO1 =16070;
SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = GregorianCalendar.getInstance();
Date date = null;
for (int i=0;i < dias.size(); i++){
try {
date = formato.parse(dias.get(i));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.setTime(date);
Long dia= cal.getTimeInMillis();
dia = dia/(1000*60*60*24);
dia =dia-GUARDIACUATRO1;
int seg2 = (int) (dia % 8);
if(seg2 == 1 || seg2 == 3|| seg2== 4){
diaTrabajo.add(dias.get(i)+ "-CURRO");
}else{
diaTrabajo.add(dias.get(i)+"-LIBRE");
}
}
return diaTrabajo;
}
/* int GUARDIAUNO6 = 16075;
int GUARDIADOS7 = 16076;
int GUARDIATRES8 = 16077;
int GUARDIACUATRO1 =16070;
int GUARDIACINCO2 = 16071;
int GUARDIASEIS3 = 16072;
int GUARDIASIETE4 = 16073;
int GUARDIAOCHO5 = 16074;
*/
public int getCurrentDayOfMonth() {
return currentDayOfMonth;
}
private void setCurrentDayOfMonth(int currentDayOfMonth) {
this.currentDayOfMonth = currentDayOfMonth;
}
public void setCurrentWeekDay(int currentWeekDay) {
this.currentWeekDay = currentWeekDay;
}
public int getCurrentWeekDay() {
return currentWeekDay;
}
}
}
A parte adjunto un rar del calendario.
-
Hola de nuevo.
He dedicado algo de tiempo , y al final he conseguido casi lo que quiero. Recordando trato de hacer un calendario de trabajo. He creado un metodo que le paso un arraylist con los dias del mes en formato "dd-mm-yy" lo he llamado dias.
public List<String> diasdeTrabajo(){
int GUARDIACUATRO1 =16071;
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = GregorianCalendar.getInstance();
Date date = null;
for (int i=0; i< dias.size() ; i++){
try {
date = formato.parse(dias.get(i));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.setTime(date);
Long dia= cal.getTimeInMillis();
dia = dia/(1000*60*60*24);
dia =dia-GUARDIACUATRO1 ;
int seg2 = (int) (dia % 8);
if(seg2 == 1 || seg2 == 3|| seg2== 4){
list.add(dias.get(i)+"-CURRO");
}else{
list.add(dias.get(i)+"-WHITE");
}
}
return list;
Debajo del calendario puse un TextView donde me aparece los "dias" de mes. que siempre son correctos.
El retorno es otro arrayList "list" que es el que se utilza para crearla vista de trabajo.
Bien pues el inicio de mi proyecto es el 1 de febrero del 2014. Febrero bien(los dias de trabajo en rojo), marzo mal se me adelanta en un dia...... Asi todos los meses.....abril bien, mayo mal,junio bien, julio mal.....No encuentro el porque.
Por favor estoy ya desesperado. Ayuda por favor. No me deja adjuntar un rar Os coloco todo el codigo.
package com.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
@TargetApi(3)
public class MyCalendarActivity extends Activity implements OnClickListener {
private static final String tag = "MyCalendarActivity";
private TextView currentMonth;
private Button selectedDayMonthYearButton;
private ImageView prevMonth;
private ImageView nextMonth;
private GridView calendarView;
private GridCellAdapter adapter;
private Calendar _calendar;
@SuppressLint("NewApi")
private int month, year;
@SuppressWarnings("unused")
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yy");
private static final String dateTemplate = "MMMM yyyy";
private TextView textoprueba;
long seg ;
// ArrayList<String> prueba = new ArrayList<String>();
private String trabajo;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_calendar_view);
_calendar = Calendar.getInstance(Locale.getDefault());
month = _calendar.get(Calendar.MONTH) + 1;
year = _calendar.get(Calendar.YEAR);
Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
+ year);
selectedDayMonthYearButton = (Button) this
.findViewById(R.id.selectedDayMonthYear);
selectedDayMonthYearButton.setText("Selected: ");
prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
prevMonth.setOnClickListener(this);
currentMonth = (TextView) this.findViewById(R.id.currentMonth);
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
nextMonth.setOnClickListener(this);
calendarView = (GridView) this.findViewById(R.id.calendar);
// Initialised
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
textoprueba = (TextView)this.findViewById(R.id.textoPruebas);
}
/**
*
* @param month
* @param year
*/
private void setGridCellAdapterToDate(int month, int year) {
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
@Override
public void onClick(View v) {
if (v == prevMonth) {
if (month <= 1) {
month = 12;
year--;
} else {
month--;
}
Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
if (v == nextMonth) {
if (month > 11) {
month = 1;
year++;
} else {
month++;
}
Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
}
@Override
public void onDestroy() {
Log.d(tag, "Destroying View ...");
super.onDestroy();
}
// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener {
private static final String tag = "GridCellAdapter";
private final Context _context;
private List<String> list;
private static final int DAY_OFFSET = 1;
private final String[] weekdays = new String[] { "Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat" };
//private final String[] months = { "January", "February", "March",
// "April", "May", "June", "July", "August", "September",
// "October", "November", "December" };
private final String[] months ={"00","01","02","03","04","05","06","07","08","09","10","11"};
private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
private int daysInMonth;
private int currentDayOfMonth;
private int currentWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
"dd-MM-yy"); //"dd-MMM-yyyy"
private List<String>dias;
private List<String>diaTrabajo;
String[] day_color ;
String theday ;
String themonth ;
String theyear;
String[]dias_curro;
String dcurro;
String mcurro;
String acurro;
// Days in Current Month
public GridCellAdapter(Context context, int textViewResourceId,
int month, int year) {
super();
this._context = context;
this.list = new ArrayList<String>();
Log.d(tag, "==> Passed in Date FOR Month: " + month + " "
+ "Year: " + year);
Calendar calendar = Calendar.getInstance();
setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());
this.dias = new ArrayList<String>();
this.diaTrabajo= new ArrayList<String>();
// Print Month
printMonth(month, year);
// Find Number of Events
eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
// diasdeTrabajo();
}
private String getMonthAsString(int i) {
return months[i];
}
private String getWeekDayAsString(int i) {
return weekdays[i];
}
private int getNumberOfDaysOfMonth(int i) {
return daysOfMonth[i];
}
public String getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
/**
* Prints Month
*
* @param mm
* @param yy
*/
private void printMonth(int mm, int yy) {
Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
int trailingSpaces = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = mm - 1;
String currentMonthName = getMonthAsString(currentMonth);
daysInMonth = getNumberOfDaysOfMonth(currentMonth);
Log.d(tag, "Current Month: " + " " + currentMonthName + " having "
+ daysInMonth + " days.");
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);
Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());
if (currentMonth == 11) {
prevMonth = currentMonth - 1;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 0;
prevYear = yy;
nextYear = yy + 1;
Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else if (currentMonth == 0) {
prevMonth = 11;
prevYear = yy - 1;
nextYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 1;
Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else {
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = yy;
prevYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
}
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
trailingSpaces = currentWeekDay;
Log.d(tag, "Week Day:" + currentWeekDay + " is "
+ getWeekDayAsString(currentWeekDay));
Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);
if (cal.isLeapYear(cal.get(Calendar.YEAR)))
if (mm == 2)
++daysInMonth;
else if (mm == 3)
++daysInPrevMonth;
// Trailing Month days
for (int i = 0; i < trailingSpaces; i++) {
Log.d(tag,
"PREV MONTH:= "
+ prevMonth
+ " => "
+ getMonthAsString(prevMonth)
+ " "
+ String.valueOf((daysInPrevMonth
- trailingSpaces + DAY_OFFSET)
+ i));
list.add(String
.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET)
+ i)+ "-"
+ getMonthAsString(prevMonth)
+ "-"
+ prevYear+ "-GREY" );//+ "-GREY"
}
// Current Month Days
for (int i =1; i <= daysInMonth; i++) {
Log.d(currentMonthName, String.valueOf(i) + " "
+ getMonthAsString(currentMonth) + " " + yy);
dias.add(String.valueOf(i)+"-"+getMonthAsString(currentMonth)+ "-"+yy );
}
if(getMonthAsString(currentMonth) !=null){
diasdeTrabajo();
}
/* if (i == getCurrentDayOfMonth()) {
list.add(String.valueOf(i) + "-"+ getMonthAsString(currentMonth) + "-" + yy+"-BLUE");//
} else {
list.add(String.valueOf(i) + "-"+ getMonthAsString(currentMonth) + "-" + yy+"-WHITE" );//+"-WHITE"
}*/
// Leading Month days
for (int i = 0; i < list.size() % 7; i++) {
Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
list.add(String.valueOf(i + 1) + "-"
+ getMonthAsString(nextMonth) + "-" + nextYear+"-GREY" );//+"-GREY"
}
}
/**
* NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
* ALL entries from a SQLite database for that month. Iterate over the
* List of All entries, and get the dateCreated, which is converted into
* day.
*
* @param year
* @param month
* @return
*/
private HashMap<String, Integer> findNumberOfEventsPerMonth(int year,
int month) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
@Override
public long getItemId(int position) {
return position;
}
public List<String> diasdeTrabajo(){
int GUARDIACUATRO1 =16071;
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = GregorianCalendar.getInstance();
Date date = null;
for (int i=0; i< dias.size() ; i++){
try {
date = formato.parse(dias.get(i));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.setTime(date);
Long dia= cal.getTimeInMillis();
dia = dia/(1000*60*60*24);
dia =dia-GUARDIACUATRO1 ;
int seg2 = (int) (dia % 8);
if(seg2 == 1 || seg2 == 3|| seg2== 4){
list.add(dias.get(i)+"-CURRO");
}else{
list.add(dias.get(i)+"-WHITE");
}
}
return list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.screen_gridcell, parent, false);
}
// Get a reference to the Day gridcell
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(this);
// ACCOUNT FOR SPACING
Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
day_color = list.get(position).split("-");
theday = day_color[0];
themonth = day_color[1];
theyear = day_color[2];
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null)) {
if (eventsPerMonthMap.containsKey(theday)) {
num_events_per_day = (TextView) row
.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
// Set the Day GridCell
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"
+ theyear);
textoprueba.setText("Estos son los dias de del mes "+dias);
if (day_color[3].equals("GREY")) {
gridcell.setTextColor(getResources()
.getColor(R.color.lightgray));
}
if (day_color[3].equals("WHITE")) {
gridcell.setTextColor(getResources().getColor(
R.color.black));
}
if (day_color[3].equals("CURRO")) {
gridcell.setTextColor(getResources().getColor(R.color.orrange));
}
return row;
}
@Override
public void onClick(View view) {
String date_month_year = (String) view.getTag();
selectedDayMonthYearButton.setText("Selected: " + date_month_year);
Log.e("Selected date", date_month_year);
try {
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
/* int GUARDIAUNO6 = 16076;
int GUARDIADOS7 = 16077;
int GUARDIATRES8 = 16078;
int GUARDIACUATRO1 =16071;
int GUARDIACINCO2 = 16072;
int GUARDIASEIS3 = 16073;
int GUARDIASIETE4 = 16074;
int GUARDIAOCHO5 = 16075;
*/
public int getCurrentDayOfMonth() {
return currentDayOfMonth;
}
private void setCurrentDayOfMonth(int currentDayOfMonth) {
this.currentDayOfMonth = currentDayOfMonth;
}
public void setCurrentWeekDay(int currentWeekDay) {
this.currentWeekDay = currentWeekDay;
}
public int getCurrentWeekDay() {
return currentWeekDay;
}
}
}
-
No me deja mandar el archio rar del proyecto. Se lo puedo mandar donde me digan.
-
Hola de nuevo. He intentado seguir el hilo pero he debido crear otro.... un desastre.
He creado un proyecto en java con solamente el metodo donde calculo los dias de trabajo, que es el que me esta dando los errores. El codigo es:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
public class Calendario {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
GregorianCalendar cal = new GregorianCalendar();
int año = 2014;
int mes = 00;
int diaa = 01; //
Calendar calendar = new GregorianCalendar(año,mes,diaa);
long fecha = calendar.getTimeInMillis();
String dias = "01-03-2015";
Date date = null;
date = formato.parse(dias );
cal.setTime(date);
long dia = cal.getTimeInMillis();
dia =dia-fecha;
dia=dia/(1000*60*60*24);
int seg2 = (int) (dia % 8);
if(seg2 ==1 || seg2 == 3|| seg2== 4){
System.out.print("Trabajo el:"+ dia);
}else{
System.out.print("No trabajo el dia:"+ dia);
}
}
}
Las variables año, mes y diaa son el inicio del calculo: 1 de enero de 2014
En el String dia voy introduciendo fechas a ver que resultado me da.
Te comentaba que me daba buenos resultados un mes si y otro no....
Y me aparecen cosas muy estrañas:
Cuando introduzco el "29-03-2015" me da 452 y trabajo. Pero al meter "30-03-2015" me da tambien 452 y obviamente trabajo.
Luego hice la prueba de 28 de febrero es decir "28-01-2015" me da 392 y no trabajo.
Meto el dia siguiente 01-02-2015 y me da 396 y trabajo. Es decir que el "01" no es febrero sino un mes de 31 dias porque cuenta el 29,30,31.
Luego el 31-02-2015 me da 426 y el 01-03-2015 me da 424 dos dias menos.
A que se debe esto? Me falta codigo?. Como puedo arregrarlo?
Gracias de nuevo.
-
Hola, es un poco lioso con los índices, porque los días del mes van de 1 a 31 pero los días transcurridos desde el inicio empiezan en cero. Si llamamos valor a los días transcurridos desde el inicio tendríamos la cadencia: trabajo, libre,trabajo,trabajo, libre, libre, libre, libre.
si valor % 8 = 7 entonces el tipo de día es libre
si valor % 8 = 6 entonces el tipo de día es libre
si valor % 8 = 5 entonces el tipo de día es libre
si valor % 8 = 4 entonces el tipo de día es libre
si valor % 8 = 3 entonces el tipo de día es trabajo
si valor % 8 = 2 entonces el tipo de día es trabajo
si valor % 8 = 1 entonces el tipo de día es libre
si valor % 8 = 0 entonces el tipo de día es trabajo
He modificado los dígitos (en lugar de 1, 3, 4 usar 0, 2, 3) y he hecho una pequeña prueba que parece que funciona bien:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
public class Calendario {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
GregorianCalendar cal = new GregorianCalendar();
int año = 2014;
int mes = 00;
int diaa = 01; //
Calendar calendar = new GregorianCalendar(año,mes,diaa);
long fecha = calendar.getTimeInMillis();
for (int i=1; i<=30;i++) {
String dias = i+"-01-2014";
Date date = null;
date = formato.parse(dias );
cal.setTime(date);
long dia = cal.getTimeInMillis();
dia =dia-fecha;
dia=dia/(1000*60*60*24);
int seg2 = (int) (dia % 8);
if(seg2 ==0 || seg2 == 2|| seg2== 3){
System.out.println("Trabajo el:"+ dia + " (El dia "+ i + " del mes)");
}else{
System.out.println("No trabajo el dia:"+ dia + " (El dia "+ i + " del mes)");
}
}
}
}
Saludos
-
Hola.
Utilizo los digitos 1,3,4 porque me da valido ciertos meses.
Al correr el metodo que me ha pasado me sige dando los mismos problemas:"Cuando introduzco el "29-03-2015" me da 452 y trabajo. Pero al meter "30-03-2015" me da tambien 452 y obviamente trabajo.Luego hice la prueba de 28 de febrero es decir "28-01-2015" me da 392 y no trabajo.Meto el dia siguiente 01-02-2015 y me da 396 y trabajo. Es decir que el "01" no es febrero sino un mes de 31 dias porque cuenta el 29,30,31.
Luego el 31-02-2015 me da 426 y el 01-03-2015 me da 424 dos dias menos."
En la aplicacion he creado un TexView debajo del calendario. Le voy a pasar un archivo donde aparece la variable "dias" que es la entrada en formato de los dias del mes:
Es el primer archivo adjunto."febrero". Luego le paso otro con la salida del metodo con los dias de trabajo y no trabajo. Y vera el mes de marzo como la cadencia desaparece, en circulo rojo estan lo que tendria que ser.
Cada vez entiendo menos. Por donde puedo seguir.
Gracias.
No me deja adjuntar: Le dejo un enlace para visualizarlo:
https://www.dropbox.com/s/wmusvg8mm3k93li/dias.png?dl=0
https://www.dropbox.com/s/xuho254nl9q8vmq/feb-marzo.jpg?dl=0,
-
Hola, lo he estado mirando y parte de los problemas pueden tratarse con cierta facilidad y otra parte no.
Cadencia: T-L-T-T-L-L-L-L
Código que he utilizado para las pruebas:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
public class Calendario {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
dameCalendario("-01-2014");
dameCalendario("-02-2014");
dameCalendario("-03-2014");
}
public static void dameCalendario(String mesYaño) throws ParseException {
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
GregorianCalendar cal = new GregorianCalendar();
int año = 2014;
int mes = 00;
int diaa = 01; //
Calendar calendar = new GregorianCalendar(año,mes,diaa);
long fecha = calendar.getTimeInMillis();
System.out.println("MES ES: "+mesYaño);
for (int i=1; i<=31;i++) {
String dias = i+mesYaño;
Date date = null;
date = formato.parse(dias );
System.out.print(" Ahora date vale: "+ date + " . ");
cal.setTime(date);
long dia = cal.getTimeInMillis();
dia =dia-fecha;
dia=dia/(1000*60*60*24);
System.out.print(" Ahora dia vale: "+ dia);
int seg2 = (int) (dia % 8);
System.out.print(" El resto de dia entre 8 es: "+ seg2 + " . ");
if(seg2 ==0 || seg2 == 2|| seg2== 3){
System.out.println("T-Trabajo el:"+ dia + " (El dia "+ i + " del mes)");
}else{
System.out.println("L-Libre el dia:"+ dia + " (El dia "+ i + " del mes)");
}
}
}
}
Parte tratable: algunas de las fechas que estás relacionando son fechas que no existen, por ejemplo el 31 de febrero de 2015. Estas fechas no deberían intervenir en un programa porque no tienen sentido. Java maneja las fechas que no existen a través de la propiedad lenient mode. lenient mode por defecto está activado, lo que significa que el 31 de febrero de 2015 será tratado como el día válido más próximo (dando un resultado sin sentido donde parece que se pierde la cadencia).
Por ejemplo para los últimos días de febrero de 2014 y comienzo de marzo de 2015 tendríamos esto
L-Libre el dia:52 (El dia 22 del mes)
L-Libre el dia:53 (El dia 23 del mes)
L-Libre el dia:54 (El dia 24 del mes)
L-Libre el dia:55 (El dia 25 del mes)
T-Trabajo el:56 (El dia 26 del mes)
L-Libre el dia:57 (El dia 27 del mes)
T-Trabajo el:58 (El dia 28 del mes)
T-Trabajo el:59 (El dia 29 del mes) - NO VALIDO
L-Libre el dia:60 (El dia 30 del mes) - NO VALIDO
L-Libre el dia:61 (El dia 31 del mes) - NO VALIDO
MES ES: -03-2014
T-Trabajo el:59 (El dia 1 del mes)
L-Libre el dia:60 (El dia 2 del mes)
L-Libre el dia:61 (El dia 3 del mes)
L-Libre el dia:62 (El dia 4 del mes)
L-Libre el dia:63 (El dia 5 del mes)
Si eliminas los días no válidos, la cadencia se respeta y los resultados son válidos.
Parte difícilmente tratable:
Si analizamos los últimos días de marzo de 2014 tendríamos esto:
T-Trabajo el:80 (El dia 22 del mes)
L-Libre el dia:81 (El dia 23 del mes)
T-Trabajo el:82 (El dia 24 del mes)
T-Trabajo el:83 (El dia 25 del mes)
L-Libre el dia:84 (El dia 26 del mes)
L-Libre el dia:85 (El dia 27 del mes)
L-Libre el dia:86 (El dia 28 del mes)
L-Libre el dia:87 (El dia 29 del mes)
T-Trabajo el:88 (El dia 30 del mes)
T-Trabajo el:88 (El dia 31 del mes) - FALLA, TENDRÍA QUE SER LIBRE Y PONE QUE TRABAJO
El problema aquí parece estar relacionado con que en algunas versiones de Java a la hora de calcular la duración del día toma en consideración el cambio horario de ciertos países (según configuración local) que se produciría por ejemplo en el 31 de marzo. Esto da lugar a que el cálculo de milisegundos no se haga con 24 horas, sino con 23 horas, y el redondeo al calcular el resto hace que lo considere como si en lugar de día 31 fuera día 30. Esto podría corregirse pero...
Recomendación: las clases de java.util.Date y Calendar han pasado a considerarse problemáticas. Para trabajar un problema de este tipo debe usarse java 8 y el paquete java.time.*
Aquí se comenta algo al respecto: http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=619:clase-calendar-y-gregoriancalendar-java-conversion-de-fechas-ejemplos-cambios-desde-java-8-cu00925c&catid=58:curso-lenguaje-programacion-java-nivel-avanzado-i&Itemid=180
En resumen, más que fallo tuyo diría que es fallo de Java. El hecho de que Java estaba fallando lo demuestra el que hayan creado una nueva parte del api con nuevas clases para tratar el tiempo en las nuevas versiones. Si lo que había en anteriores versiones hubiera funcionado bien no lo hubieran cambiado.
Por tanto, ¿por dónde seguir? -- > Usar java 8 con las nuevas clases del paquete java.time
Saludos
-
Hola. Lo primero muchisimas gracias porque utilizando java 8 con java.time. el problema aparentemente desaparece.
Bien pero ahora quieroutilizarlo en android, en el proyecto que tengo y no exixte la Clse ni los import. Cimo puedo solucionar esto? Tengo que empezar de cero?. Me he descargado el eclipse luna que mirando si acepta java8 pero importo el proyecto y tampoco nada.
Y ahora que?
Muchisimas gracias de nuevo.
-
Hola lo primero pega el código Java que constituye la solución, será justo para quien haya leído o colaborado en el hilo poder ver la solución... quizás ayude a otras personas con problemas similares.
-
Perdon. La variable i la doy un valor de 10 porque con 1 me da error.
Tambien los meses que tienen 30 dias. Pero para comprobar los errores anteriores es suficiente.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Calendario {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
dameCalendario("2015-01-");
//dameCalendario("2015-02-");
dameCalendario("2015-03-");
// dameCalendario("2015-04-");
dameCalendario("2015-05-");
dameCalendario("2015-07-");
}
public static void dameCalendario(String mesYaño) throws ParseException {
LocalDate hoy = LocalDate.now();
LocalDate inicio = LocalDate.of(2014, Month.FEBRUARY,1);
LocalDate inicio2 = LocalDate.parse("2014-02-01");
//Period dif = Period.between(hoy, inicio);
long dif = ChronoUnit.DAYS.between(inicio,hoy);
for (int i=10; i<=31;i++) {
String dias =mesYaño+i;
LocalDate diatrabajo = LocalDate.parse(dias);
long dia = ChronoUnit.DAYS.between(inicio,diatrabajo);
System.out.print(" Ahora dia vale: "+dia);
int seg2 = (int) (dia % 8);
System.out.print(" El resto de dia entre 8 es: "+ seg2 + " . ");
if(seg2 ==1 || seg2 == 3|| seg2== 4){
System.out.println("T-Trabajo el:"+ diatrabajo );
}else{
System.out.println("L-Libre el dia:"+ diatrabajo );
}
}
}
}
Gracias
-
Gracias. Para el paso a android no sé decirte con exactitud cómo podría hacerse... Este ejemplo parece estar bien: http://examples.javacodegeeks.com/android/core/activity/android-timertask-example/
Supongo que tendrás que buscar la forma de trasladarlo, o bien programarlo manualmente ::) Si hay algún experto en android por ahí a ver si nos puede echar una mano.
-
Hola de nuevo, creo que lo voy solucionando. Ya consigo que los import aparezca java.time.
He hecho esto:i solved this problem by trying following solution
Project > Properties > Java Build Path
Select Libraries tab
Select JRE System Library
Click Edit button
Choose an alternate JRE (jre1.8.0_20)
Click Finish button
Si alguien lo necesita que me lo diga ,porque soy muy necio y no tengo muy claro lo que he hecho configurando el eclipse.
Gracias de nuevo y reportare el resultado si es ok???? que lo pongo en duda; habra mas problemas.
-
Hola Alex.
Creí que nunca lo iba a poder decir, pero este tema lo hemos solucionado. Han pasado muchos dias pero no lo puedo dedicar mucho tiempo a la semana. Ademas de mi torpeza.....
Bien al parecer eclipse o android no trabaja con java 8. Con lo cual no podia emular el proyecto, me daba unos errores indescriptibles...Alguien me aconsejo que utilizara esta libreria;http://www.joda.org/joda-time/. Asi lo hice y despues de no pocos problemas (el eclipse lo estoy cogiendo panico) todo salió. El metodo dichoso queda asi: public List<String> diasdeTrabajo() {
LocalDate hoy =LocalDate.now();
LocalDate inicio = LocalDate.parse("2014-02-01");
for (int i = 0; i < dias.size(); i++) {
String[] dateArr = dias.get(i).split("-"); // date format is yyyy-mm-dd
String diaa = dateArr[0];
String mes = dateArr[1] ;
String año = dateArr[2];
int mess= Integer.parseInt(dateArr[1])+1;
String messs = String.valueOf(mess);
String diac = diaa+"-"+ messs +"-"+año;
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy");
LocalDate diasdeTrabajo =LocalDate.parse(diac, dtf);
Days dia = Days.daysBetween(inicio, diasdeTrabajo);
int days = dia.getDays();
int seg2 = days % 8;
if (seg2 == 1 || seg2 == 3 || seg2 == 4) {
list.add(dias.get(i) + "-CURRO");
} else {
list.add(dias.get(i) + "-WHITE");
}
}
return dias;
}
Hay lineas de codigo en el ciclo for que las tengo que utilizar porque me daba problemas con los meses despues de novienbre(tamaño de un array).
Gracias a gente como vosotros, principiantes como yo pueden tener satisfaciones como la que tuve el otro dia cuando por fin me salio el calendario. Muchas gracias por el tiempo que me has dedicado. Yo seguire con mi proyecto,pero con la seguridad que me da el saber que no estoy solo.
Lo dicho, gracias por existir y hasta la proxima.
-
Hola, me he alegrado al leer tu mensaje. Mi enhorabuena pues aunque te ha costado bastante tiempo, al final lo has logrado. El mérito es tuyo. Cuenta siempre con que desde estos foros intentaremos ayudar en la medida de nuestras posibilidades. Suerte!!