2
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 :)

Rediner
  • 83
  • 1
  • 7
  • Be a little more specific, when you say `screen` do you mean Application? When you say `app crashes` do you mean app crashes when launched or when the button is clicked? Then there's the question of `onClick()` which view gets the `onClick()`? You haven't set any click listener on any view. – Abbas Oct 07 '16 at 13:07
  • I have several screens, every one of them works fine, but when i try to open (by click on a button) a screen with this music player, app crashes and turns off. Onclick doesnt matter in this concern and works fine – Rediner Oct 07 '16 at 13:13

0 Answers0