简体   繁体   English

如何在AndroidStudio中从原始文件夹播放mp3file时修复java.lang.NullPointerException?

[英]How do i fix java.lang.NullPointerException in playing mp3files from a raw folder in AndroidStudio?

I wanted to created a playlist such that when the user clicks on the song, it plays and when he clicks on the next song, the song that is playing will stop and resume the next song. 我想创建一个播放列表,以便当用户单击该歌曲时播放,而当他单击下一首歌曲时,正在播放的歌曲将停止并恢复下一首歌曲。 Additionally, i have placed a stop button which also stops the song which is being played. 此外,我还放置了一个停止按钮,该按钮也可以停止正在播放的歌曲。 Now, here is the problem when i write the following block of code, my program crashes and my error log shows java.lang.NullPointerException- 现在,当我编写以下代码块时,这就是问题,我的程序崩溃了,错误日志显示了java.lang.NullPointerException-

 public void playSong(int res)
    {
        if(mp.isPlaying()) {
            mp.reset();
            mp = MediaPlayer.create(getApplicationContext(), resid[res]);
            mp.start();
        }

        else {
            mp = MediaPlayer.create(getApplicationContext(), resid[res]);
            mp.start();
        }


    }

But if i change the code to the following, it works fine. 但是,如果我将代码更改为以下代码,则效果很好。 I see that mp.reset() is the issue. 我看到mp.reset()是问题。 But I dont know how to fix it because without it the when i click on a song and there is already a song which is playing, both the songs play at the same time.- 但是我不知道如何解决它,因为如果没有它,当我单击一首歌曲并且已经有一首歌曲正在播放时,两首歌曲会同时播放。

   public void playSong(int res)
    {
            mp = MediaPlayer.create(getApplicationContext(), resid[res]);
            mp.start();
     }

//Following is my full code. //以下是我的完整代码。 Please help me to fix the bug. 请帮助我修复错误。 Thanks-- 谢谢 -

package com.example.user.musicp;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    Button b;
    private MediaPlayer mp;
    private ListView v;
    private int [] resid = {R.raw.k,R.raw.u};
    private String [] name = {"k","u"};

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

        v = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);

        v.setAdapter(adapter);
        b = (Button) findViewById(R.id.StopButton);

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              //  mp.stop();
              //  mp.release();
                onDestroy();

            }
        });

        v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                playSong(i);
              //  mp = MediaPlayer.create(MainActivity.this, resid[i]);
              //  mp.start();
            }
        });

    }

        public void playSong(int res)
    {
        if(mp.isPlaying()) {
            mp.reset(); //this is where the issue begins
            mp = MediaPlayer.create(getApplicationContext(), resid[res]);
            mp.start();
        }

        else {
            mp = MediaPlayer.create(getApplicationContext(), resid[res]);
            mp.start();
        }


    }

    @Override

    public void onDestroy() {

        super.onDestroy();
        mp.release();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

在此处输入图片说明

References:- http://www.geeks.gallery/how-to-play-mp3-file-from-raw-folder-in-a-listview-android/ 参考资料:-http: //www.geeks.gallery/how-to-play-mp3-file-from-raw-folder-in-a-listview-android/

After some valuable suggestion by some users, i edited my code and was able to fix the bug. 经过一些用户的宝贵建议后,我编辑了代码,并能够修复该错误。 But here is the thing when i click on a song and there is a previous song which is already playing, i want the previous song to stop and the new song to be played but unfortunately both the songs keep playing. 但是,当我单击一首歌曲并且已经播放了上一首歌曲时,这是事情,我希望上一首歌曲停止播放并播放新歌,但不幸的是,这两首歌仍在播放。 I tried every possible means to fix it but i may be doing mistake somewhere. 我尝试了所有可能的方法来修复它,但是我可能在某个地方犯了错误。 Here is my edited code and when i implement the following, then my program crashes. 这是我编辑的代码,当我实现以下代码时,程序崩溃。 PLease help me out - 请帮我-

 public void playSong(int res)
    {



        boolean isplaying = mp.isPlaying();

         if(isplaying)
         {
             mp.stop();
             mp = MediaPlayer.create(getApplicationContext(), resid[res]);
             mp.start();
         }

         else
         {
             mp = MediaPlayer.create(getApplicationContext(), resid[res]);
             mp.start();
         }

}

Here is the complete working code just in case someone gets stuck in the future. 这是完整的工作代码,以防万一将来有人卡住。 Thanks a lot to StackOverflow users for helping me out. 非常感谢StackOverflow用户帮助我。 Cheers! 干杯!

package com.example.user.musicp;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.io.IOException;

public class MainActivity extends Activity {

    Button b,c;
    private MediaPlayer mp;
    private ListView v;
    private int [] resid = {R.raw.k,R.raw.u};
    private String [] name = {"k","u"};

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

        v = (ListView) findViewById(R.id.listView);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);

        v.setAdapter(adapter);
        b = (Button) findViewById(R.id.StopButton);
        c = (Button) findViewById(R.id.next);


        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp.stop();


            }
        });

        c.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent in = new Intent("com.example.user.musicp.SPLASH");
                startActivity(in);
            }
        });
        v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                playSong(i);
              //  mp = MediaPlayer.create(MainActivity.this, resid[i]);
              //  mp.start();
            }
        });

    }

        public void playSong(int res)
    {
        mp.reset();// stops any current playing song

        mp = MediaPlayer.create(getApplicationContext(), resid[res]);// create's
        mp.start(); // starting mediaplayer






    }

    @Override

    public void onDestroy() {

        super.onDestroy();
        mp.release();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
if(mp.isPlaying()) { // mp only declared (still null)
    mp.reset();
    mp = MediaPlayer.create(getApplicationContext(), resid[res]);
    mp.start();     }

else {
    mp = MediaPlayer.create(getApplicationContext(), resid[res]);
    mp.start();
}

I suppose that at the moment of the if statement mp is only declared. 我想在if语句mp的时候才声明。 That's why you can not do mp.isPlaying() because mp is still null . 这就是为什么您不能执行mp.isPlaying()原因,因为mp仍然为null

That should explain why in this case it works fine 那应该解释为什么在这种情况下它可以正常工作

public void playSong(int res)
{
    // here mp is still null
    mp = MediaPlayer.create(getApplicationContext(), resid[res]); // From here on we can use mp
    mp.start();
 }

Here mp is not used before initialization, hence no null pointer exception. 这里mp在初始化之前不使用,因此没有空指针异常。

EDIT : Creating the mediaplayer in the playSong method is a bit weird. 编辑:在playSong方法中创建mediaplayer playSong This means every time playSong is called mp gets reassigned. 这意味着每次调用playSong都会重新分配mp A better place could be in the class' constructor. 更好的地方可能是在类的构造函数中。 Doing so you can be sure mp will not be null when playSong gets invoked. 这样做可以确保在调用playSongmp不会为null

EDIT 2 : You're still reassigning mp in playSong . 编辑2:您仍在playSong重新分配mp I would suggest to do this : 我建议这样做:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mp = MediaPlayer.create(getApplicationContext(), resid[res]);
    // ...
}

And I would implement playSong like this : 我会像这样实现playSong

public void playSong(int songIndex)
{
    if(mp.isPlaying()) {
        mp.pause(); // Pause the current track
    }

    mp.selectTrack(songIndex); // Select the requested track
    mp.start();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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