[英]Fragment recreation before activity.onServiceConnected gives me a NPE
我的一个片段具有一个列表视图,该片段列表开始时会从我的服务中获取他的适配器。 在正常的生命周期中,它没有问题,但是当我旋转设备时,显示的片段甚至在活动重新创建之前就被重新创建,因此我在活动上的服务实例尚未准备好,仅在onServiceConnected()之后才准备就绪。 即使我尝试恢复并在fragment.onResume()中设置此适配器,也无法保证该服务已被绑定。 在我的代码中,我负责在方向更改后(在onServiceConnected()之后)添加片段,但是片段生命周期不遵守此顺序。 为什么在活动之前重新创建片段?
我该怎么办?
活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
actionBar = getSupportActionBar();
drawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerlayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.END);
Intent it = new Intent(this, MyService.class);
if (!MyService.RUNNING) {
startService(it);
}
bindService(it, this, 0);
}
@Override
public void onServiceConnected(ComponentName name, IBinder binderservice) {
Crashlytics.log(Log.INFO, TAG_ACTIVITY_LIFECYCLE,
"Activity onServiceConnected");
LocalBinder binder = (LocalBinder) binderservice;
this.service = binder.getService();
//load a fragment with a radio player
carregaRadio();
if (!service.isIRCConnected()) {
// load a fragment to login on a chat
carregaLogin();
} else {
// load fragments according to the chat
// variables on the service when service was already
// running before activity creation.
carregaChatdoService();
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
即使活动被销毁,片段实例也会保留或保存。 这就是我通过在活动onCreate
添加OnGlobalLayoutListener
来解决类似问题的方式。 你的问题可能会有点不同,所以你可以绑定在服务onGlobalLayout
当onServiceConnected
被调用时,你的片段应该是随时可以使用。
viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.d("Activity", "onGlobalLayout");
if ( musicService != null)
tabPagerAdapter.getPlaylistFragment().loadPlaylist(musicService.getPlaylist());
viewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.