Search code examples
androidfor-looptextviewrunnable

Displaying array of items on a textview


I need to display many String values from an Array in a TextView. I am using Runnable for this. But it runs only once! If I put a for loop the code throws error.

Runnable hMyTimeTask = new Runnable() {
    public void run() {
        nCounter++;
        label.setText(rates[nCounter]);
    }
};

try {
    handler.removeCallbacks(hMyTimeTask);
    handler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
    e.printStackTrace();
}

Using a for loop:

Runnable hMyTimeTask = new Runnable() {
    public void run() {
        for (int i = 0; i < rates.length; i++) {
            label.setText(rates[i]);
        }
    }
};

try {
    handler.removeCallbacks(hMyTimeTask);
    handler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
    e.printStackTrace();
}

Solution

  • I am using runnable for this. but it runs only once!

    Inside your Runnable you need to post your Runnable again to repeat it:

    Runnable hMyTimeTask = new Runnable() {
        public void run() {
            nCounter++;
            if(nCounter >= rates.length)
                nCounter = 0;
            label.setText(rates[nCounter]);
    
            // Run this again
            handler.postDelayed(this, 1000); // delay 1 second
        }
    };