gpt4 book ai didi

java - FragmentTransaction 抛出空引用

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:40 25 4
gpt4 key购买 nike

我有加载器 fragment ,并且正在从加载器 fragment 调用另一个 fragment 。一切正常,但突然我的 fragment 加载器给我一个错误。在加载器 fragment 中,我显示进度条 5 秒,之后将显示另一个 fragment 。

这是我的代码:-

加载器fragment.java

package com.example.user.attendance;
public class Loader_fragment extends Fragment {
AVLoadingIndicatorView Loader;
Runnable runnable;
Handler handler;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Timer timer;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View loadder_fragment=inflater.inflate(R.layout.fragment_loader_fragment, container, false);

Loader=(AVLoadingIndicatorView)loadder_fragment.findViewById(R.id.loder_login);
handler=new Handler();
runnable=new Runnable() {
@Override
public void run() {
Loader.setVisibility(View.INVISIBLE);
timer.cancel();
fragmentManager=getFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.slide_in_left,R.animator
.slide_out_left,R.animator.slide_in_right,R.animator.slide_out_right);
Home_Screen home_screen=new Home_Screen();
fragmentTransaction.replace(R.id.Home_screen_fragment,home_screen);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

}


};

timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(runnable);
}
}, 5000,5000);


/* if(Loader.setVisibility(View.INVISIBLE)==1){


}*/

return loadder_fragment;
}


}

Logcat 显示错误:-

 Process: com.example.user.attendance, PID: 1200
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
at com.example.user.attendance.Loader_fragment$1.run(Loader_fragment.java:44)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7402)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

为什么它在 fragment 中显示空对象引用。

最佳答案

不要在onCreateView中执行View操作。相反,请将其移至 onViewCreated 方法。 原因:您的 fragment 尚未设置 View 。

此外,替换:

fragmentManager = getFragmentManager();

具有以下内容:

fragmentManager = getChildFragmentManager();

关于java - FragmentTransaction 抛出空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com