在处理从主活动到片段的通信时,我遇到了这个问题。监视器一直说:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.mick.myApplication.FragmentCal.readfiles(java.util.LinkedList)' on a null object reference
at com.example.mick.myApplication.main.onCreate(main.java:101)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
这是片段事务和发送消息的代码:
fragmentinfo = new FragmentInfo();
fragmentcal = new FragmentCal();
fragmentrep = new FragmentRep();
fragmentdicn = new FragmentDicn();
fragmentManager = getSupportFragmentManager();
if (!fragmentcal.isAdded()) {
if (currentFragment == null) {
fragmentManager.beginTransaction().add(R.id.fragmentlayout, fragmentcal).commit();
} else {
fragmentManager.beginTransaction().hide(currentFragment).add(R.id.fragmentlayout, fragmentcal).commit();
}
FragmentCal fragmentCal = (FragmentCal) getSupportFragmentManager().findFragmentById(R.id.fragmentlayout);
fragmentCal.readfiles(nameList);
} else {
fragmentManager.beginTransaction().hide(currentFragment).show(fragmentcal).commit();
}
currentFragment = fragmentcal;
为此,我为所有活动和片段导入android.support.v4.app.Fragment。
答案 0 :(得分:0)
在将片段添加到活动之前,您无法执行findFragmentById。当您创建setContentView时,Activity会使布局膨胀并将其视图添加到当前窗口。在此布局中具有Fragment的情况下,将其与xml中提供的给定Id或Tag一起添加到FragmentManager中。只有在这一刻你才能在那里找到它。所以你要做的就是将findFragmentById移到setContentView下面。
来源:NullpointerException when findFragmentById
希望它有所帮助!祝你好运!