0

I have a TextView on my splash screen and I'm trying to emulate Discord's randomized loading text.

I have the following code, pulled from here:

    private void LoadText() {

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            final TextView loadingTextView = findViewById(R.id.loading);
            loadingTextView.setText(FetchRandomLoadingText());
        }
    };


    ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
    ex.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);

}

FetchRandomLoadingText() returns a string from an ArrayList by index, works fine (tested with Toast to make sure it wasn't the problem).

This is working fine for one or two updates, but if the splash takes longer (slow internet connection for example) to do its thing, the text stops updating after 2 iterations.

I've looked at the equivalent of setInterval in JavaScript for Java but the solutions seems to iterate once and then stop all together.

Am I missing something obvious in getting this to endlessly run until I flag for a new Activity to be loaded?

James Gould
  • 4,492
  • 2
  • 27
  • 50
  • Are you sure about FetchRandomLoadingText? May it return same data after 2 iterations? – logcat Feb 02 '18 at 00:05
  • There's a large enough data set for it to be unlikely, but I see what you're saying. I've had it running on my S8 for about 5 minutes now and the text hasn't changed past the 2nd iteration's updated text. – James Gould Feb 02 '18 at 00:06

2 Answers2

2

I'd use a handler instead of a scheduler.

long delay = 5000; //5 seconds
final TextView loadingTextView = findViewById(R.id.loading);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        loadingTextView.setText(FetchRandomLoadingText());
        handler.postDelayed(this, delay);
    }
};
handler.post(runnable);

I would also test to make sure FetchRandomLoadingText() runs like you expect it to. Maybe run it 20 times and print the results in a dummy activity

0

Andrew's code is what I've been using in production but with a slight change. I did some profiling on the code during execution and noticed a slight memory leak if my splash screen didn't change to the main activity (by design when I found the bug). I left the above code running for around 20 minutes by mistake, and found that the app began running 10s of mb over what should be realistic for a simple Activity with a TextView.

The altered, memory leak free code should have handler and runnable declared at a class level and instantiated in the onCreate function, rather than inside the local execution block. Doing so not only prevents the memory leak, but also executes faster.

James Gould
  • 4,492
  • 2
  • 27
  • 50