gegobyte
gegobyte

Reputation: 5565

How to update TextView by infinitely looping through String Array values?

I have created a string array in strings.xml with 5 strings. This is how I have initialized it:

adLoopValues = findViewById(R.id.ad_loop_values); // TextView
adValues = getResources().getStringArray(R.array.banner_ad_values);

Using the code in this answer, I am looping through them:

final android.os.Handler handler = new android.os.Handler();
    handler.post(new Runnable() {

        int i = 0;

        @Override
        public void run() {
            adLoopValues.setText(adValues[i]);
            i++;
            if (i == adValues.length) {
                i = 0;
            } else {
                //5 sec
                handler.postDelayed(this, 1000 * 5);
            }
        }
});

The above code works for the first time, it shows first string in string array and then after 5 seconds shows the next one and goes to the last one. To loop it infinitely, I have put if block and reset i to 0 so after last string, it can again start from first value but that is not happening, after the last string is displayed, nothing happens. It doesn't start from first value.

Upvotes: 1

Views: 59

Answers (2)

Fawzan
Fawzan

Reputation: 4849

You can simply have the delay and calculate the index with modulo.

final android.os.Handler handler = new android.os.Handler();
    handler.post(new Runnable() {

        int i = 0;

        @Override
        public void run() {
            adLoopValues.setText(adValues[i % addValues.length]);


            handler.postDelayed(this, 1000 * 5);
            i++;
        }
});

Upvotes: 0

Stanislav Bondar
Stanislav Bondar

Reputation: 6265

You don't restart handler in

if (i == adValues.length) {
            i = 0;
        }

remove else and use handler.postDelayed(this, 1000 * 5); after if block

Upvotes: 1

Related Questions