我正在为即将到来的生日开发一个Android应用程序。我有一种方法可以检查SQLite数据库中的日期是否在两天内即将到来的生日并加载到列表中。还有两个片段:MainFragment和BirthdayFragment。启动应用程序时,我希望BirthdayFragment仅在列表中包含某些内容时显示,而在没有列表时应显示MainFragment。但是,当我使用下面的代码启动该应用程序时,它显示为空活动。当列表为空或不为空时,我尝试了此操作。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check for upcoming birthday here...
//if we have birthday, display Birthday Fragment
DatabaseOperations dbo = new DatabaseOperations(getApplicationContext());
List<Student> studentList = dbo.getAllStudentsToList();
if (studentList.isEmpty())
//if we don't have any birthday, display main fragment
if (savedInstanceState == null) {
MainFragment fragment = new MainFragment();
replaceFragment(fragment);
}
else {//if we have any birthday, display birthday fragment
BirthdayFragment birthdayFragment = new BirthdayFragment();
replaceFragment(birthdayFragment);
}
}
但是,如果删除代码以检查即将到来的生日,它将很好地显示MainFragment。代码是:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
MainFragment fragment = new MainFragment();
replaceFragment(fragment);
}
}
下面是替换片段的方法
public void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
请帮助我。