-1

I want to infinitely loop a method when in the Main Fragment, but I keep getting issues saying the return or the loop is unreachable or I may throw and exception. Should I be using try / catch / finally?

Any ideas help!

View v = inflater.inflate(R.layout.fragment_main, container, false);

return v;

while (true) { // This line is unreachable

    aMethod();

}
Michael
  • 9,639
  • 3
  • 64
  • 69

2 Answers2

1

You can't run code after a return statement. The function has ended. Consider changing your loop to break on a condition, and to return after your loop has terminated.

EDIT: Using a thread

new Thread()
{
    public void run()
    {
        while(true)
            yourActivity.runOnUiThread(new Runnable()
            {
                public void run()
                {
                    doStuff();
                }
            });
    }
}.start();
return returnVal;
MeetTitan
  • 3,383
  • 1
  • 13
  • 26
  • That's the thing. It will never terminate. I want it to loop forever. – Michael Dec 16 '14 at 17:18
  • I've tried one and it didn't work. (I may have written it incorrectly) Could you write an example? – Michael Dec 16 '14 at 17:19
  • android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. The while statement cannon complete without throwing an exception. – Michael Dec 16 '14 at 17:24
  • @Mike, you cannot make changes to the ui from another thread. Now you need `yourActivity.runOnUiThread(Runnable yourRunnable)`. Take a look at this SO question http://stackoverflow.com/questions/11140285/how-to-use-runonuithread. I have updated my answer with an example as well. – MeetTitan Dec 16 '14 at 17:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67035/discussion-between-mike-milla-and-meettitan). – Michael Dec 16 '14 at 17:34
0

You cannot reach a statement after returning v:

return v; //Everyting after this is unreachable because you return

for (int f = 1; f > 0; f++) { // This line is unreachable

    logo.startAnimation(flipInAnimation);
    logo.startAnimation(flipOutAnimation);

}
Marv
  • 3,517
  • 2
  • 22
  • 47
  • I am aware of that. How would you recommend I get around it? – Michael Dec 16 '14 at 17:17
  • Uhm, if you are running an infinite loop you can never return something after that unless you beak out of the loop. – Marv Dec 16 '14 at 17:18
  • Then, as @MeetTitan suggested, use a thread. He provided a good example. Your question was really vague and this is what I thought you were asking. – Marv Dec 16 '14 at 17:28