Context inside a Runnable

oggy picture oggy · Oct 6, 2010 · Viewed 26.9k times · Source

I try to play a sound from R.raw. inside a Thread/Runnable But I can't get this to work.

new Runnable(){ 
  public void run() {  

    //this is giving me a NullPointerException, because getBaseContext is null  
    MediaPlayer mp = MediaPlayer.create( getBaseContext(), R.raw.soundfile);  

    while (true) {  
      if (something)  
          play something  
    }  
  }

How can I get the real Context inside the run method? It is null no matter what I try. Or is there a better way to do this?

Answer

user338519 picture user338519 · Jan 18, 2014

You should also be able to get the this reference from the outer class by using MainActivity.this.