Search code examples
javaandroidmultithreadinginfinite

I can't update more than one on my infinite thread in button click


At the below code i try to take the user's current location each second as x and y axises.At the first time of loop,the code works.But second and so on it doesnt work.What is the missing thing on this code.What should i do.Thanks..

new Thread(new Runnable(){
    @Override
    public void run() {
        while (true) {
            runOnUiThread(new Runnable() {
                public void run() {
                    textViewXAltitude.setText(String.valueOf(gps.getLatitude()));
                    textViewYAltitude.setText(String.valueOf(gps.getLongitude()));

                }
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}).start();

Solution

  • you should do this by Handler;for example:

            final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 0x123) {
                    textViewX.setText(String.valueOf(i++));
                    textViewY.setText(String.valueOf(j++));
                }
            }
        };
    
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0x123);
                    }
                }, 0, 1000);
            }
        });