Why does creating Media Player object crash my android code? -


i'm creating little program plays mario jump sound when jumps. can use z acceleration make program display message when reaches value 10 m/s^2. want play sound media player object, when create media player object, crashes code. i'll post code on pastebin.

public class mainactivity extends activity implements sensoreventlistener {         sensor accelerometer;         sensormanager sm;         textview acceleration;     mediaplayer mp = mediaplayer.create(getbasecontext(),r.raw.jump); //line 17           @override         protected void oncreate(bundle savedinstancestate) {                 super.oncreate(savedinstancestate);                 setcontentview(r.layout.activity_main);                 sm= (sensormanager)getsystemservice(sensor_service);                 accelerometer = sm.getdefaultsensor(sensor.type_accelerometer);                 sm.registerlistener(this, accelerometer, sensormanager.sensor_delay_normal);                            acceleration = (textview) findviewbyid(r.id.acceleration);                       }          @override         public boolean oncreateoptionsmenu(menu menu) {                 // inflate menu; adds items action bar if present.                 getmenuinflater().inflate(r.menu.main, menu);                 return true;         }          @override         public void onaccuracychanged(sensor sensor, int accuracy) {                 // todo auto-generated method stub           }          @override         public void onsensorchanged(sensorevent event) {                 // todo auto-generated method stub                      acceleration.settext("x: " + event.values[0] + "\ny: " + event.values[1] +  "\nz: " + event.values[2]);                 if (event.values[2] > 10.8 ) {                         acceleration.settext("z big!!");                 }         }  } 

the addition of line 17 crashed program...

you need split

mediaplayer mp = mediaplayer.create(getbasecontext(),r.raw.jump); 

into 2 parts follows:

mediaplayer mp; //keep current line mp = mediaplayer.create(getbasecontext(),r.raw.jump); //put in oncreate() 

your app crashed because initializing mp outside of method body, meant executed before oncreate(). activity object not ready until oncreate() has been called, calling getbasecontext() results in nullpointerexception.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -