Reputation: 410
I'm making a music player app. When I click list item in SongsFragment.java it sends intent to PlayerActivity.java with the song position. The musicSrv is null always. I looked for Activity lifecyle on google and figured out it has something to do with this. Since I'm beginner so couldn't apply that.
SongsFragment:
@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);
}
In PlayerActivity.java:
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();
}
}
Error: I get "Attempt to invoke virtual method 'void services.MusicService.setSong(int)' on a null object reference
"
Upvotes: 0
Views: 80
Reputation: 1006644
First, onCreate()
is called before onStart()
. musicSrv
will be null
, because you have not called bindService()
yet.
Second, bindService()
itself is asynchronous. It will be some time later before your onServiceConnected()
method is called.
You cannot use musicSrv
until you assign that field a value, and you cannot do that until inside of onServiceConnected()
at the earliest.
So, move your calls related to musicSrv
into onServiceConnected()
or some later event, after you know that musicSrv
should be ready.
Also, do not call bindService()
directly, as that will get you in trouble with configuration changes with this activity. Call bindService()
(and, later, unbindService()
) using the Application
object (e.g., getApplicationContext().bindService()
).
Upvotes: 1