Мне нужно сделать приложение, чтобы при нажатии на картинку появлялся звук. Я пишу на Java (Android Studio).
package com.example.project_1;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
private ImageView img1, img2;
private MediaPlayer sound1, sound2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img1=(ImageView)findViewById(R.id.image1);
img2=(ImageView)findViewById(R.id.image2);
sound1=MediaPlayer.create(this, R.raw.sn1);
sound2=MediaPlayer.create(this, R.raw.sn2);
imageClick();
}
public void imageClick() {
img1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
SoundPlay(sound1);
}
}
);
img2.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
SoundPlay(sound2);
}
}
);
}
public void SoundPlay(MediaPlayer allsounds) {
allsounds.start();
}
}
Код скомпилирован, но при нажатии на изображение в эмуляторе происходит сбой приложения. в логах нашел это:
2019-06-01 21:15:08.408 13431-13431/? E/ample.project_: Unknown bits set in runtime_flags: 0x8000
2019-06-01 21:15:08.798 13431-13453/? E/vndksupport: Could not load /vendor/lib/egl/libGLES_emulation.so from sphal namespace: dlopen failed: library "/vendor/lib/egl/libGLES_emulation.so" not found.
2019-06-01 21:15:08.798 13431-13453/? E/libEGL: load_driver(/vendor/lib/egl/libGLES_emulation.so): unknown
2019-06-01 21:15:09.798 13431-13452/com.example.project_1 E/EGL_emulation: tid 13452: eglQueryString(923): error 0x3008 (EGL_BAD_DISPLAY)
2019-06-01 21:15:17.712 13431-13447/com.example.project_1 E/MediaPlayerNative: error (1, -2147483648)
2019-06-01 21:15:17.715 13431-13431/com.example.project_1 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.project_1, PID: 13431 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference at
com.example.project_1.MainActivity.SoundPlay(MainActivity.java:51) at
com.example.project_1.MainActivity$2.onClick(MainActivity.java:43) at
android.view.View.performClick(View.java:7251) at
android.view.View.performClickInternal(View.java:7228) at
android.view.View.access$3500(View.java:802) at
android.view.View$PerformClick.run(View.java:27843) at
android.os.Handler.handleCallback(Handler.java:883) at
android.os.Handler.dispatchMessage(Handler.java:100) at
android.os.Looper.loop(Looper.java:214) at
android.app.ActivityThread.main(ActivityThread.java:7116) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)