V
V
Vadim Popov2018-05-17 20:02:58
Java
Vadim Popov, 2018-05-17 20:02:58

Why doesn't Timer work in Thread?

Implemented sending the user's coordinates to the server, in the UI thread without TIMER the code is working, now I'm trying to run the thread every 5 seconds, below is the listing

private void refreshUserCoordinates(final Context contextThread) {
    Intent intent = getIntent();
    final String user = intent.getStringExtra("user");
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            GeoPosition geoPosition = new GeoPosition();
            geoPosition.SetUpLocationListener(contextThread);
            ServerInteraction serverInteraction = new ServerInteraction("http://razdvatri/refreshCoordinates.php",
                    "{\"user\" " + ":\"" + user + "\", \"latitude\" " + ":\"" + geoPosition.getLatitude() + "\", \"longitude\" :" + "\"" + geoPosition.getLongitude() + "\"" + "}", "put");
            serverInteraction.execute();
        }
    }, 0L, 50L * 1000);
}

Here is what LogCat says

util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) 05-17 16:14:30.306 5372-5372/popovvad.findme D/AndroidRuntime: Shutting down VM 05 -17 16:14:30.307 5372-5372/popovvad.findme I/Process: Sending signal. PID: 5372 SIG: 9

I understand that the main error is described here -

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Popov, 2018-05-17
@vadimpopov94

It helped in the end in the run () method to add

if (Looper.myLooper() == null){
     Looper.prepare();
 }

Full listing
private void refreshUserCoordinates(final Context contextThread) {
    Intent intent = getIntent();
    final String user = intent.getStringExtra("user");
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (Looper.myLooper() == null)
            {
                Looper.prepare();
            }
            GeoPosition geoPosition = new GeoPosition();
            geoPosition.SetUpLocationListener(contextThread);
            ServerInteraction serverInteraction = new ServerInteraction("http://razdvatri.ru/refreshCoordinates.php",
                    "{\"user\" " + ":\"" + user + "\", \"latitude\" " + ":\"" + geoPosition.getLatitude() + "\", \"longitude\" :" + "\"" + geoPosition.getLongitude() + "\"" + "}", "put");
            serverInteraction.execute();
        }
    }, 0L, 50L * 1000);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question