英文:
How to pass Activity.class (this) to a method? (Android)
问题
在我的MainActivity类中,我有一个用于播放音乐的小函数:
MediaPlayer player1;
if(player1 == null){
player1 = MediaPlayer.create(this, R.raw.song1);
player1.start();
}
这很好地工作,但我想在其他活动中也使用它,所以我创建了一个MusicPlayer类:
MediaPlayer player;
public void play(Context c, @RawRes int sound){
if (player == null){
player = MediaPlayer.create(c, sound);
}
player.start();
}
因此,我想做的是将R.raw.song
传递给play()
方法。我可以通过参数@RawRes int sound
传递它。
我的问题是,我如何传递this
?
我在我的MainActivity类中尝试了这个:
MusicPlayer playboy;
playboy.play(this, R.raw.song1);
但是我得到一个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.japan, PID: 32764
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.japan/com.example.japan.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.japan.Helper.MusicPlayer.play(android.content.Context, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3333)
我还尝试了传递MainActivity.this
,但是出现了相同的错误。
我做错了什么?
英文:
In my MainActivity class I have this little function to play music
MediaPlayer player1;
if(player1 == null){
player1 = MediaPlayer.create(this, R.raw.song1);
player1.start();
}
It works very fine but I want to use this for other activty too so I created a MusicPlayer class
MediaPlayer player;
public void play(Context c, @RawRes int sound){
if (player == null){
player = MediaPlayer.create(c, sound);
}
player.start();
}
So what I want to do is, to pass a R.raw.song
to the play()
method. I could pass it by the parameter @RawRes int sound
What my problem is, how can I pass this
?
I tried this in my MainActivity Class
MusicPlayer playboy;
playboy.play(this, R.raw.song1);
But I get an error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.japan, PID: 32764
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.japan/com.example.japan.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.japan.Helper.MusicPlayer.play(android.content.Context, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3333)
I also tried to pass MainActivity.this
but same error.
What am I doing wrong?
答案1
得分: 0
你需要首先创建你的MusicPlayer对象。在你的MainActivity类中尝试以下代码:
MusicPlayer playboy = new MusicPlayer();
playboy.play(this, R.raw.song1);
英文:
You need to create your MusicPlayer object first. Try this code in your MainActivity class
MusicPlayer playboy = new MusicPlayer();
playboy.play(this, R.raw.song1);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论