D
D
Denis Karakchiev2015-09-09 18:49:22
Android
Denis Karakchiev, 2015-09-09 18:49:22

Problem with Handler();, how to solve without implementing standard methods?

An example from the book Head First Android Development (2015) (not a translation, save me XOR). The bottom line is that the Handler is used to ensure that the method occurs on the main thread, or does not interfere with it (until you fully understand it), the method itself, described below, is called in onCreate();. The compiler swears that the Handler is supposedly abstract, so you need to actually implement its internals, but judging by the continuation in the book "As we can see, the application works just fine on the emulator", much better, except Compilation failed = _=
Method directly (everything with comments, I think you can understand what I want from it):

private void runTimer() {
        final TextView timeView = (TextView)findViewById(R.id.time_view); // get the text view
        final Handler handler = new Handler(); // create a new Handler
        handler.post(new Runnable() { //call the post() method, passing in a new Runnable. The post() method
                                     //process codes without a delay, so the code in Runnable will
                                     //run almost immediately
            @Override
            public void run() {     //the Runnable run() method contains the code you want to be run. In
                //our case the code to update the text view.
                int hours = seconds / 3600;                                           //format the seconds into
                int minutes = (seconds % 3600) / 60;                                    //hours, minutes, and seconds.
                int secs = seconds % 60;                                              //Just plain Java code.
                String time = String.format("%d:%02d:%02d", hours, minutes, secs);  //

                timeView.setText(time); // set the text view text

                if (running) {   // if running is true, increment
                    seconds++;  // the seconds variable
                }
                handler.postDelayed(this, 1000); //Post the code in the Runnable to be run again after a delay
                                                //of 1000 milliseconds, or 1 second. At this line of code it
                                                 //included in the runnable run() method, this will keep getting called.
            }
        });
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Emin, 2015-09-09
@Satori_Kanzo

Most likely you imported the wrong Handler. There are a lot of them, check the imports.
I took one hundred percent from the logging package, but I need it fromandroid.os

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question