Search code examples
androidmultithreadingsettextandroid-runonuithread

runOnUiThread settext only works at the first time during a loop


I have an ArrayList of Textviews populated by an expandListAdpater, my goal is to change the values of the textViews, but for some reason it works only once. I tried different timers, tried to tie my handler to the ui thread, it never works. here is my code. Please help! Expandlistadapter…

TextView mytexts= ButterKnife.findById(view, R.id.mytexts);
mySubSections.add(new ConstructForKeepingTextviewsForUpdate(mytexts));
// I got about 10 more textviews , this is an example

public class ConstructForKeepingTextviewsForUpdate {
    private TextView getTextviewToBeUpdated() {
        return textviewToBeUpdated;
    }

    public void SetVal(String t){
        getTextviewToBeUpdated().setText(t);
    }


    TextView textviewToBeUpdated;

    public ConstructForKeepingTextviewsForUpdate(TextView textviewToBeUpdated) {
        this.textviewToBeUpdated = textviewToBeUpdated;
        }

}

in onCreate I run this

private void pleaseWork(){
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    updateNumbersInLoop();
                }
            });
        }
    }, 0, 1000);
}

public static void updateNumbersInLoop() {
    for (ConstructForKeepingTextviewsForUpdate subSec : mySubSections){
       String datext = dbHelper.getValue (computedValue);
       subSec.SetVal(datext); 
    }
}
//The getValue function works , I can see the correct value, but the settext works only once, at the first time.

Solution

  • Actaully as I played with the code, asyncTask gave the same result. Apparently you can't pass textview as an object, for some reason. So what actually works is

    TextView myTextV=  (TextView) findViewById(ConstructForKeepingTextviewsForUpdate.getItsID());
    myTextV.setText("anything you like");
    

    what you should do is pass the id as integer.