Android Media Player空指针异常

时间:2017-02-16 17:16:46

标签: java android

我知道我尝试使用

的空指针异常是什么
MediaPlayer mp = new MediaPlayer();

 public int check()
  {
if(mp!=null)
    {
        return 1;
    }
    else
    {
        return 2;
    }

   }

没有帮助。   这是我得到的错误 -

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {com.openaisearch.www.musicplayer / com.openaisearch.www.musicplayer.MainActivity}:   java.lang.NullPointerException:尝试调用虚方法   ' boolean com.openaisearch.www.musicplayer.Music.check()'在null   对象参考

 public class MainActivity extends AppCompatActivity {
   ArrayList<String> mSongsList = new ArrayList<>() ;
  ArrayList<Long> SongsPath =  new ArrayList<>() ;
  Button btnPlay;
  Music mService;
SeekBar seekBar;
ListView lv;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        Music.LocalBinder binder = (Music.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};

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

    Intent intent = new Intent(this, Music.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    startService(intent);

    btnPlay = (Button) findViewById(R.id.buttonPlay);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    lv = (ListView) findViewById(R.id.list);
    getAudioList();
    ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mSongsList);
    lv.setAdapter(arrayAdapter);
    onSongClick();
    setSeekBar();
    check();
}



@Override
protected void onStop() {
    super.onStop();
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}


public void getAudioList() {
    String orderBy = MediaStore.Audio.Media.TITLE ;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media._ID }, selection, null, orderBy);

    int count = mCursor.getCount();
    while (mCursor.moveToNext()) {
        mSongsList.add(mCursor.getString(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
        SongsPath.add(mCursor.getLong(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
    }
    mCursor.close();
}

public void onSongClick()
{

   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          mService.playSong(SongsPath.get(position));
           if(btnPlay.getText() == "Play")
           {
               btnPlay.setText("Pause");
           }
       }
   });
}

public void onButtonClick(View view) {
  int a =  mService.stopMusic();
    if(a == 1)
    {
        btnPlay.setText("Play");
    }
    else if (a ==2)
    {
        btnPlay.setText("Pause");
    }
}
 public void check()
 {
     boolean check = mService.check();
 }
public void setSeekBar()
{
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser )
            {
                  mService.setProg(progress*1000);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}


}

服务 -

  public class Music extends Service {

Long b;
MediaPlayer mp;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
   Music getService() {

        return Music.this;
    }
}

public void playSong(Long a) {
    if (a!= b)
    {   if(mp!=null)
          {
              mp.stop();
              mp.release();
              mp=null;
          }
        b =a;
        Uri contentUri = ContentUris.withAppendedId(
                android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, a);
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mp.setDataSource(getApplicationContext(), contentUri);
            mp.prepare();
            mp.setLooping(true);
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   }


public int stopMusic()
{
    if(mp.isPlaying())
    {
        mp.pause();
        return 1;
    }
    else if (mp!=null)
    {
        mp.start();
        return 2;
    }
    else
    {
        return 0;
    }
}


public void setProg(int a)
{   if(mp!=null)
    {
    mp.seekTo(a);
    }

}

public boolean check()
{
    if(mp!=null)
        {
            return true;
        }
        else
        {
            return false;
        }

}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
 }

4 个答案:

答案 0 :(得分:0)

你可能从这一行获得了NPE:boolean check = mService.check();所以它mService为空,而不是mp

答案 1 :(得分:0)

我认为您尝试绑定尚未启动的服务。尝试在startService(intent);

之前致电bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

答案 2 :(得分:0)

您的服务类应遵循以下格式;覆盖onCreate()方法

您正在获取NPE,因为mService在行中为空:mService.check();

    public class MyService extends Service {
    private Binder binder;  

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new Binder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class Binder extends android.os.Binder {
        public MyService getService() {
            return MyService.this;  // return instance
        }
    }
}

答案 3 :(得分:0)

您没有在ur函数中使用mbound检查服务是否已连接到活动。

           public void check()
              {
                    i f(mBound)
                   {
             boolean check = mService.check();
                   }
             }