Skip to content Skip to sidebar Skip to footer

Context Inside A Runnable

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,

Solution 1:

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

Solution 2:

You should use getBaseContext. Instead, if this runnable is within an activity, you should store the context in a class variable like this:

publicclassMainActivityextendsActivity {
    private Context context;

    publicvoidonCreate( Bundle icicle ) {
        context = this;


        // More Code
    }

    // More codenewRunnable(){ 
        publicvoidrun() {  
            MediaPlayermp= MediaPlayer.create(context, R.raw.soundfile);  

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

Also you shouldn't have an infinite loop like that playing a sound over and over - there should be a sleep in there in order to prevent the sound from playing over and over in a small amount of time and overlapping the same sounds with each other.

Solution 3:

I guess you need to create a Thread and call Thread.start().

Solution 4:

You need to declare a Handler object in your UI thread.

Then in your Thread use

YourHandler.post(new Runnable() {
    publicvoidrun() {
        //do something to the UI (i.e. play something)
    }});

Solution 5:

This works for me:

void doo {
        handler.post(runnable);
 }

 privatefinalHandlerhandler=newHandler();
 privatefinalRunnablerunnable=newRunnable() {
        @Overridepublicvoidrun() {
             foo(getApplicationContext());  // do something with Context
        }
 };

Post a Comment for "Context Inside A Runnable"