【发布时间】:2020-04-02 14:08:48
【问题描述】:
在我的通知片段上实现了一个回收器视图,在相同的片段上添加项目没有问题,但是当我尝试从另一个片段添加项目时,它抛出并错误 JavaNullPointException。
这是我的具有回收站视图的片段
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);
notimodels = new ArrayList<> ();
mRecyclerView = v.findViewById(R.id.notificationsRecycler);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
// get data from the notificiation
return v;
}
@Override
public void onStart() {
super.onStart ();
swipeRefreshLayout.setRefreshing(true);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
}
public void fillNotification(int mImage, String mtext, String mtext2, String mDate)
{
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager (getContext ());
mAdapter = new NotificationAdapter (notimodels);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
notimodels.add (0,new NotificationModel (mImage,mtext,mtext2,mDate));
}
}
**当我尝试从其他片段(例如 tis)调用函数时“”
NotificationFragmentCict notificationFragmentCict =new NotificationFragmentCict ();
notificationFragmentCict.fillNotification (R.drawable.bursar, "Bursar", "your clreard","min");
我的应用程序崩溃并抛出此错误
Process: com.univibezstudios.ocappservice.ocapp, PID: 3380
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
问题是这个 显示此错误是因为您的片段视图尚未创建。这就是为什么 recyclerview 为 null 并且您在 null recyclerview 上调用 setHasFixedSize(...) 方法的原因。但我无法解决它任何帮助家伙
【问题讨论】:
-
当你这样创建一个新的fragment时:“new NotificationFragmentCict()”,onCreateView方法没有被调用,因为布局没有被膨胀,所以没有recycler view。 (尝试在 onCreateView 中放置一个断点,看看它是否在初始化之后被调用)。您需要使用片段管理器在某处为片段充气
标签: android android-fragments android-recyclerview