私は音楽プレーヤーアプリを作っています。 SongsFragment.javaでリストアイテムをクリックすると、SongAnd.javaにインテントが送信されます。 musicSrvは常にnullです。私はgoogleでActivity lifecyleを探して、これと何か関係があると考えました。私は初心者なので、それを適用できませんでした。サービスオブジェクトが初期化されていない/呼び出されていないonServiceCreated
SongsFragment:PlayerActivity.javaで
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//musicSrv.setSong(position);
//musicSrv.playSong();
Intent intent = new Intent(getContext(), PlayerActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
:
public class PlayerActivity extends AppCompatActivity {
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private static final String POS = "pos";
private int passedPos;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
passedPos = extras.getInt("pos",0);
musicSrv.setSong(passedPos);
musicSrv.playSong();
setContentView(R.layout.activity_player);
}
ServiceConnection musicConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//Get service
musicSrv = binder.getService();
//Pass list
ArrayList<Song> songs = ((DataFetcher)getApplicationContext()).songList;
musicSrv.setList(songs);
musicBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
@Override
public void onStart() {
super.onStart();
if(playIntent==null) {
playIntent = new Intent(this,(Class)MusicService.class);
bindService(playIntent,musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
@Override
public void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}
エラー:私はまず、onCreate()
がonStart()
前に呼び出され、 "Attempt to invoke virtual method 'void services.MusicService.setSong(int)' on a null object reference
"
ありがとうございます!私はmusicSrv関連のステートメントをonServiceConnected()に移動しました。曲は再生されています。 –