-1

I have a problem with my app crashing when i try this code? I want i to constantly checking for if the MediaPlayer (MP) is playing, and if it is I want a Text to read "Now Playing" - But if it aint playing i want it to read "Not Playing".

I dont get any warnings from Eclipse, but still when i export it, it crashes on load. I know the code for setting the TextView isnt there but that isnt the problem. ( i think ) If there is an other way to do this i would be glad for a push in the right direction.

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
                      //The Timer
                                Thread playingtimer = new Thread (){
                                    public void run() {
                                        try{
                                            int time = 1;
                                            while(time > 0) {
                                            sleep(100);

                                            if (MP.isPlaying()){ 
                                //set the TextView here "Now Playing"
                                            }
                                            else 
                                //set the TextView to "NOT Playing"
                                            }
                                        } 
                                        catch (InterruptedException e) {
                                        e.printStackTrace();
                                        }
                                        finally{

                                        }
                                    }
                                };
                                playingtimer.start();
ZimZux
  • 29
  • 5

2 Answers2

1

I know the code for setting the TextView isnt there but that isnt the problem. ( i think )

That is precisely the problem. You are trying to update a View from a background Thread. You should be using runOnUiThread(), Handler, or AsyncTask for updating the UI.

These answers talk about handler and asynctask

Example of runOnUiThread

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

The issue here is that if you are trying to modify your TextView from that timer it will crash, because one of the most important rules in android is that you just cannot modify any views from any thread other than the main, and you are trying to change it from your custom worker thread, in order to make it work, wrap the code that is modifying the view into a runOnUIThread method, or come up with your own Handler mechanism to run that code in the main Thread.

Hope this helps.

Regards!

Martin Cazares
  • 13,637
  • 10
  • 47
  • 54