简体   繁体   中英

Trying to PlaySound onTouch, getting crash. Android

I'm new in android programming and now I'm trying to do my homework. I read all the similar topics here, but it looks like I'm missing something. I need to play some wav sound from raw folder using onTouch for my button. Here's my code.

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {



    Button bullButton = (Button) findViewById(R.id.button1);
    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bullButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    mp = MediaPlayer.create(MainActivity.this,R.raw.bull);
                    mp.start();
                }
                else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    mp.stop();
                }

                return true;
            }
        });

    }


}

The problem is - I get crash every time I try to launch my app.

I have a crash-log here:

12/06 17:03:15: Launching app
Cold swapped changes.
$ adb shell am start -n "com.foxysoft.soundplayonclick/com.foxysoft.soundplayonclick.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.foxysoft.soundplayonclick.test | com.foxysoft.soundplayonclick
Waiting for application to come online: com.foxysoft.soundplayonclick.test | com.foxysoft.soundplayonclick
Waiting for application to come online: com.foxysoft.soundplayonclick.test | com.foxysoft.soundplayonclick
Connecting to com.foxysoft.soundplayonclick
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1393)
I/InstantRun: Instant Run Runtime started. Android package is com.foxysoft.soundplayonclick, real application class is null.
W/art: Failed to find OatDexFile for DexFile /data/data/com.foxysoft.soundplayonclick/files/instant-run/dex/slice-slice_1-classes.dex ( canonical path /data/data/com.foxysoft.soundplayonclick/files/instant-run/dex/slice-slice_1-classes.dex) with checksum 0x69cf59e0 in OatFile /data/data/com.foxysoft.soundplayonclick/cache/slice-slice_1-classes.dex
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.foxysoft.soundplayonclick, PID: 5533
                  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.foxysoft.soundplayonclick/com.foxysoft.soundplayonclick.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                      at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                      at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                      at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                      at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
                      at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:205)
                      at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
                      at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525)
                      at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:193)
                      at com.foxysoft.soundplayonclick.MainActivity.<init>(MainActivity.java:15)
                      at java.lang.reflect.Constructor.newInstance(Native Method)
                      at java.lang.Class.newInstance(Class.java:1606)
                      at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:135) 
                      at android.app.ActivityThread.main(ActivityThread.java:5254) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:372) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

I looked this topic: Play sound continuously onTouch()

Looks like I did the same, what's wrong?

Well this:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.foxysoft.soundplayonclick/com.foxysoft.soundplayonclick.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

And change your code to this:

Button bullButton;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bullButton = (Button) findViewById(R.id.button1); // you need the R.layout.activity_main to be loaded to make a connection to it!
    bullButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                mp = MediaPlayer.create(MainActivity.this,R.raw.bull);
                mp.start();
            }
            else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mp.stop();
            }

            return true;
        }
    });
}

If you still get an error this way, please share the error log with us. (well formatted question btw!)

I think the problem is with your MediaPlayer

mp = MediaPlayer.create(MainActivity.this,R.raw.bull);

Just put this line of code outside the touchListener like this

bullButton = (Button) findViewById(R.id.button1);
mp = MediaPlayer.create(MainActivity.this,R.raw.bull);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
               bullButton.setOnTouchListener(new View.OnTouchListener() {
               @Override
               public boolean onTouch(View view, MotionEvent motionEvent) {

                 if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                       mp.start();
                  }
                  else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        mp.stop();
                  }

                  return true;
                 }
           });
        }
});

I think it's the findViewById you're doing , put in inside the oncreate after

Button bullButton ;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bullButton = (Button) findViewById(R.id.button1);
    bullButton.setOnTouchListener(...

you can't do findviewbyid before the activity is created , simple as that .

try it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM