Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView Text Not Updating

package com.aviyehuda.test.multithreading;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MultithreadingTest extends Activity {
Button btn;
private Handler myHandler;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn = (Button) findViewById(R.id.Button01);
}

public void buttonClicked(View v) {
    myHandler = new Handler();
    MyThread mThread = new MyThread();
    mThread.start();
}

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 30; i++) {
            myHandler.post(new NewThreaad(i));
        }
    }
}
class NewThreaad implements Runnable{
    int i;
    public NewThreaad(int n) {
        i=n;
    }
        @Override
        public void run() {
            ((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
}
}

I have code mentioned above but getting result Hello29 on TextView but i want Hello1,Hello2,hello3.................Hello29 one by one automatically

Please give me hint what I am doing wrong

like image 891
Jignesh Ansodariya Avatar asked Sep 18 '25 19:09

Jignesh Ansodariya


2 Answers

A couple of things.

First, after changing the text, you should call invalidate on the TextView to force a refresh.

Second, to do operation on the UI, you should run that in the UI thread. Use runOnUiThread

like image 188
Matthieu Avatar answered Sep 21 '25 11:09

Matthieu


Well, the main problem is that you're not appending you are overwriting. Instead of

 ((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);

do

  TextView tv = ((TextView) findViewById(R.id.TextView01));
  String text = tv.getText().toString();
  tv.setText(text + " Hello:" + i);
like image 38
dmon Avatar answered Sep 21 '25 10:09

dmon