package com.example.android.appname;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class SampleActivity extends Activity {
Button b1;
MediaPlayer player=MediaPlayer.create(Activity.this,R.raw.sound);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
b1 = (Button)findViewById(R.id.button1);
b1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN);
player=MediaPlayer.create(DisplayActivity.this,R.raw.sound);
player.start();
else if (event.getAction() == MotionEvent.ACTION_UP)
player=MediaPlayer.create(DisplayActivity.this,R.raw.sound);
player.stop();
return true;
}
});}
public void onClick(View view) {
Intent intent = new Intent(this, Activity.class);
startActivity(intent);
}
}
When I try to open a screen with the button playing sound, app crashes and in logcat appears something like this:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.appname/com.example.android.appname.'NAME'Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Also 'else' in 'else if' goes redlined and says: 'else' without 'if'
Please tell me what should I do to make this work :)