Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating UI on button click after a certain time
    primarykey
    data
    text
    <p>I have a TextView. I want to update its text (append a "1") after 1 second of a button click.</p> <pre><code>public class HaikuDisplay extends Activity { Method m; Timer t; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); t = new Timer(); m = HaikuDisplay.class.getMethod("change"); } //Event handler of the button public void onRefresh(View view) { //To have the reference of this inside the TimerTask final HaikuDisplay hd = this; TimerTask task1 = new TimerTask(){ public void run(){ /* * I tried to update the text here but since this is not the UI thread, it does not allow to do so. */ //Calls change() method m.invoke(hd, (Object[])null); } }; t.schedule(task1, 1000); } public void change() { //Appends a "1" to the TextView TextView t = (TextView)findViewById(R.id.textView1); t.setText(t.getText() + "1"); } //Event handler of another button which updates the text directly by appending "2". //This works fine unless I click the first button. public void onRefresh1(View view) { TextView t = (TextView)findViewById(R.id.textView1); t.setText(t.getText() + "2"); } } </code></pre> <p>Consider all Exceptions be handled.</p> <p>On first click, <code>m.invoke</code> gives <code>InvocationTargetException</code>. But it calls the method <code>change()</code> on successive invokes without any Exceptions(verified by logging). But it does not update the text. Where am I wrong?</p> <p>Also, I see in the debugger that it creates a new Thread every time I click the button. That is fine. But why isn't it removing the previous Threads though their execution has been completed?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload