当前,我正在使用Android Studio 3.1.2和SDK 19编码一个android项目。
当我重构几乎所有代码并用getContext()
替换了许多requireContext()
调用,并用getActivity()
替换了requireActivity()
时,我遇到了问题,该应用程序已经崩溃在启动器活动中。我知道有几篇关于获取IllegalStateException: Fragment myFragment not attached to a context
的相同问题的文章,但它们都是针对特定项目的,因此实际上并没有向我展示我错过的步骤。因此,我在此向您展示我的代码示例,并祈求一个能使我感到启发的仁慈的程序员,我要做的就是以适合的方式解决此问题。
这是我的SplashActivity
(启动器活动):
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Fragment fragmentToDisplay = null;
if (!(getIntent().getBooleanExtra("isLaunch", true))) {
fragmentToDisplay = new LoginFragment();
} else {
if (savedInstanceState == null) {
fragmentToDisplay = new SplashFragment();
}
}
if (fragmentToDisplay.isAdded()) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentToDisplay).commit();
}
}
}
这是SplashFragment
,最初会被加载:
public class SplashFragment extends RequestingFragment {
private Handler delayHandler = new Handler();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_splash, container, false);
requestQueue = Volley.newRequestQueue(this.requireContext());
requestParams.add(SessionHandler.getAppInstanceID(this.getContext()));
startRequest(RequestOperation.SESSION_CHECK);
onSuccess(new JSONObject(), "");
return fragmentView;
}
@Override
public void onDestroy() {
super.onDestroy();
delayHandler.removeCallbacksAndMessages(null);
}
@Override
public void onSuccess(final JSONObject json, String parsingKey) {
delayHandler.postDelayed(new Runnable() {
@Override
public void run() {
//parsing stuff
}
}, 2000);
}
@Override
public void onError() {
showErrorDialog();
}
private void showErrorDialog() {
//show a horrifying dialog
}
}
如果有人可以向我解释,特别是什么原因导致了异常以及如何正确执行,我将非常感激。预先感谢。