Runnable + Difference of Dates + Person Starting with Android

0

I am currently starting with an Android course, and after learning how to handle XML, I am starting with Java. Well, you always try to reach more than you can cover and enjoy doing some application to have fun before seeing it in the course, my problem is probably Android 1, but there you go.

I want to obtain the difference between two dates and that is shown on the screen until the difference in seconds. Ok, that achieved with a class public void ObtenerFecha() ; but now I want to go a step further and that the difference in dates is constantly updated, and that every second that elapses, this difference will be increased on the screen. Well I have put with the Runnable but I can not show the text in TexView .

I paste the code of discord:

import android.net.ParseException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.os.Handler;



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    String fechaInicio = "15-01-2017 11:30:00";

    Handler handler = new Handler();

    private Runnable runnableCode = new Runnable() {
        @Override
        public void run() {


            class ObtenerFecha {
                public void main(String[] args) {

                    try {
                        //Fecha de Inicio
                        SimpleDateFormat stringDate1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        Date DateInicio = stringDate1.parse(fechaInicio);
                        Calendar CalendarInicio = new GregorianCalendar();
                        CalendarInicio.setTime(DateInicio);

                        //Obtener fecha actual
                        Calendar CalendarActual = new GregorianCalendar();
                        Date DateActual = CalendarActual.getTime();
                        SimpleDateFormat stringDate2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        String fechaActual = stringDate2.format(DateActual);

                        // tomamos la instancia del tipo de calendario

                        Calendar stringCalendarActual = Calendar.getInstance();


                        // obtenemos el valor de las fechas en milisegundos
                        long milisegundos1 = CalendarInicio.getTimeInMillis();
                        long milisegundos2 = CalendarActual.getTimeInMillis();
                        // tomamos la diferencia
                        long diffMilisegundos = milisegundos2 - milisegundos1;


                        // calcular la diferencia en segundos
                        long diffSegundos = Math.abs(diffMilisegundos / 1000);
                        long diferenciasegundos = diffMilisegundos % 60;

                        // calcular la diferencia en minutos
                        long diffMinutos = Math.abs(diffMilisegundos / (60 * 1000));
                        long restominutos = diffMinutos % 60;

                        // calcular la diferencia en horas
                        long diffHoras = (diffMilisegundos / (60 * 60 * 1000));
                        long restohoras = diffHoras % 24;

                        // calcular la diferencia en dias
                        long diffdias = Math.abs(diffMilisegundos / (24 * 60 * 60 * 1000));

                        String diferencia = diffdias + " días \n" + restohoras + " horas \n" + restominutos + " minutos y \n" + diferenciasegundos + " segundos";

                        //Llamada para mostrar fechas
                        mostrarDiferencia(diferencia);

                    } catch (ParseException e) {
                        //Log.e(TAG, “Función obtenerFecha: Error Parse “ e);
                    } catch (Exception e) {
                        //Log.e(TAG, “Función obtenerFecha: Error “ + e);
                    }

                }

            }

            Log.d("Handlers", "Called on main thread");

            // Run the above code block on the main thread after 2 seconds
            handler.postDelayed(runnableCode, 2000);
        }
    };



    private void mostrarDiferencia(String message) {
        TextView priceTextView = (TextView) findViewById(R.id.diferencia);
        priceTextView.setText(message);
    }

}
    
asked by JuanKar 11.02.2017 в 17:37
source

2 answers

0

Your code does not run because in Android Java behaves a little differently the life cycle of the Activity starts in the onCreate therefore the main method will not be executed and your code should look similar to this:

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.net.ParseException;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;

    import android.os.Handler;
    public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    runnableCode.run();

}

String fechaInicio = "15-01-2017 11:30:00";

Handler handler = new Handler();


private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {

        try {
            //Fecha de Inicio
            SimpleDateFormat stringDate1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date DateInicio = stringDate1.parse(fechaInicio);
            Calendar CalendarInicio = new GregorianCalendar();
            CalendarInicio.setTime(DateInicio);

            //Obtener fecha actual
            Calendar CalendarActual = new GregorianCalendar();
            Date DateActual = CalendarActual.getTime();
            SimpleDateFormat stringDate2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            String fechaActual = stringDate2.format(DateActual);

            // tomamos la instancia del tipo de calendario

            Calendar stringCalendarActual = Calendar.getInstance();


            // obtenemos el valor de las fechas en milisegundos
            long milisegundos1 = CalendarInicio.getTimeInMillis();
            long milisegundos2 = CalendarActual.getTimeInMillis();
            // tomamos la diferencia
            long diffMilisegundos = milisegundos2 - milisegundos1;


            // calcular la diferencia en segundos
            long diffSegundos = Math.abs(diffMilisegundos / 1000);
            long diferenciasegundos = diffMilisegundos % 60;

            // calcular la diferencia en minutos
            long diffMinutos = Math.abs(diffMilisegundos / (60 * 1000));
            long restominutos = diffMinutos % 60;

            // calcular la diferencia en horas
            long diffHoras = (diffMilisegundos / (60 * 60 * 1000));
            long restohoras = diffHoras % 24;

            // calcular la diferencia en dias
            long diffdias = Math.abs(diffMilisegundos / (24 * 60 * 60 * 1000));

            String diferencia = diffdias + " días \n" + restohoras + " horas \n" + restominutos + " minutos y \n" + diferenciasegundos + " segundos";

            //Llamada para mostrar fechas
            mostrarDiferencia(diferencia);

        } catch (ParseException e) {
            //Log.e(TAG, “Función obtenerFecha: Error Parse “ e);
        } catch (Exception e) {
            //Log.e(TAG, “Función obtenerFecha: Error “ + e);
        }

        /*
        class ObtenerFecha {
            public void main(String[] args) {

                try {
                    //Fecha de Inicio
                    SimpleDateFormat stringDate1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                    Date DateInicio = stringDate1.parse(fechaInicio);
                    Calendar CalendarInicio = new GregorianCalendar();
                    CalendarInicio.setTime(DateInicio);

                    //Obtener fecha actual
                    Calendar CalendarActual = new GregorianCalendar();
                    Date DateActual = CalendarActual.getTime();
                    SimpleDateFormat stringDate2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                    String fechaActual = stringDate2.format(DateActual);

                    // tomamos la instancia del tipo de calendario

                    Calendar stringCalendarActual = Calendar.getInstance();


                    // obtenemos el valor de las fechas en milisegundos
                    long milisegundos1 = CalendarInicio.getTimeInMillis();
                    long milisegundos2 = CalendarActual.getTimeInMillis();
                    // tomamos la diferencia
                    long diffMilisegundos = milisegundos2 - milisegundos1;


                    // calcular la diferencia en segundos
                    long diffSegundos = Math.abs(diffMilisegundos / 1000);
                    long diferenciasegundos = diffMilisegundos % 60;

                    // calcular la diferencia en minutos
                    long diffMinutos = Math.abs(diffMilisegundos / (60 * 1000));
                    long restominutos = diffMinutos % 60;

                    // calcular la diferencia en horas
                    long diffHoras = (diffMilisegundos / (60 * 60 * 1000));
                    long restohoras = diffHoras % 24;

                    // calcular la diferencia en dias
                    long diffdias = Math.abs(diffMilisegundos / (24 * 60 * 60 * 1000));

                    String diferencia = diffdias + " días \n" + restohoras + " horas \n" + restominutos + " minutos y \n" + diferenciasegundos + " segundos";

                    //Llamada para mostrar fechas
                    mostrarDiferencia(diferencia);

                } catch (ParseException e) {
                    //Log.e(TAG, “Función obtenerFecha: Error Parse “ e);
                } catch (Exception e) {
                    //Log.e(TAG, “Función obtenerFecha: Error “ + e);
                }

            }

        }
        */

        Log.d("Handlers", "Called on main thread");

        // Run the above code block on the main thread after 2 seconds
        handler.postDelayed(runnableCode, 2000);
    }
};



private void mostrarDiferencia(String message) {
    TextView priceTextView = (TextView) findViewById(R.id.diferencia);
    priceTextView.setText(message);
}


}
    
answered by 11.02.2017 / 21:19
source
0

What you do does not work in Android or in Java current. The main(String args...) method is just an entry point that you define to run a program, and even though you can implement main in several classes, to run a program you normally use an entry point no more.

You make the following mistakes:

  • you create an anonymous class object with Runnable interface, but you never use it after

  • you create a class with a main method, but as the object's method, not static

  • You define the class in the run method, and you do not use it either.

the main(String args...) method has nothing magical. It is defined with modifier static in classes to be able to launch programs. Apart from that it is any method, which could be called as MiClase.main(args) from your code, but it is very rare and generally not necessary.

I recommend you define your action that you want to run as a recording (every 2 seconds) as an internal class and launch it from onCreate in the following way:

public class MainActivity extends AppCompatActivity {

    String fechaInicio = "15-01-2017 11:30:00";
    Handler handler;
    Runnable obtenerFecha;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();
        obtenerFecha = new ObtenerFecha();
        handler.post(obtenerFecha);
    }


    private void mostrarDiferencia(String message) {
        TextView priceTextView = (TextView) findViewById(R.id.diferencia);
        priceTextView.setText(message);
    }

    class ObtenerFecha implements Runnable{
        @Override
        public void run() {
                    try {
                        //Fecha de Inicio
                        SimpleDateFormat stringDate1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        Date DateInicio = stringDate1.parse(fechaInicio);
                        Calendar CalendarInicio = new GregorianCalendar();
                        CalendarInicio.setTime(DateInicio);

                        //Obtener fecha actual
                        Calendar CalendarActual = new GregorianCalendar();
                        Date DateActual = CalendarActual.getTime();
                        SimpleDateFormat stringDate2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        String fechaActual = stringDate2.format(DateActual);

                        // tomamos la instancia del tipo de calendario

                        Calendar stringCalendarActual = Calendar.getInstance();


                        // obtenemos el valor de las fechas en milisegundos
                        long milisegundos1 = CalendarInicio.getTimeInMillis();
                        long milisegundos2 = CalendarActual.getTimeInMillis();
                        // tomamos la diferencia
                        long diffMilisegundos = milisegundos2 - milisegundos1;


                        // calcular la diferencia en segundos
                        long diffSegundos = Math.abs(diffMilisegundos / 1000);
                        long diferenciasegundos = diffMilisegundos % 60;

                        // calcular la diferencia en minutos
                        long diffMinutos = Math.abs(diffMilisegundos / (60 * 1000));
                        long restominutos = diffMinutos % 60;

                        // calcular la diferencia en horas
                        long diffHoras = (diffMilisegundos / (60 * 60 * 1000));
                        long restohoras = diffHoras % 24;

                        // calcular la diferencia en dias
                        long diffdias = Math.abs(diffMilisegundos / (24 * 60 * 60 * 1000));

                        String diferencia = diffdias + " días \n" + restohoras + " horas \n" + restominutos + " minutos y \n" + diferenciasegundos + " segundos";

                        //Llamada para mostrar fechas
                        mostrarDiferencia(diferencia);

                    } catch (ParseException e) {
                        //Log.e(TAG, “Función obtenerFecha: Error Parse “ e);
                    } catch (Exception e) {
                        //Log.e(TAG, “Función obtenerFecha: Error “ + e);
                    }
            Log.d("Handlers", "Called on main thread");

            // Run the above code block on the main thread after 2 seconds
            handler.postDelayed(ObtenerFecha.this, 2000);
        }
    }
}   

Better still, it would be to implement a way to interrupt the work to avoid updates while your app is in the background, starting the execution in onStart and interupting it in onStop .

    
answered by 11.02.2017 в 22:45