在发帖之前,我花了相当多的时间自己弄清楚,不过我已经删除了各种错误。我正在开发一个小笔记应用程序,在我的应用程序中使用包含回收视图的片段之前,一切都很好。问题是我无法将从数据库检索到的数据传递给回收视图适配器。
错误显示“尝试在空对象引用上调用虚方法‘void com.example.diary.RecyclerAdapter.setdata(java.util.List)’”
我已验证数据不为空,我很困惑为什么我会收到空指针错误。
相关代码贴在下面。
fragment.java
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_recents, container, false);
RecyclerAdapter adapter;
db = NotesDatabase.createdb(getContext());
adapter = new RecyclerAdapter(numofitems);
retrievetasks();
layoutManager = new LinearLayoutManager(getActivity());
binding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_recents);
binding.recyclerView.setLayoutManager(layoutManager);
binding.recyclerView.setAdapter(adapter);
Log.d("adapeter", "has set");
return view;
}
public void retrievetasks() {
try {
LiveData<List<NotesEntry>> notesEntries = db.Dao().loadalltasks();
notesEntries.observe(this, new Observer<List<NotesEntry>>() {
@Override
public void onChanged(List<NotesEntry> notesEntries) {
notes = notesEntries;
Log.d("sizeforall", String.valueOf(notesEntries.size()));
adapter.setdata(notesEntries); //this is where the error occures }
});
'adapter.setdata(notesEntries); //这是错误发生的地方'
adapter.java
public void setdata(List<NotesEntry> notesEntries) {
try {
notesEntryList = notesEntries;
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<NotesEntry> getnotesentries() {
return notesEntryList;
}
如果我不使用片段,则不会出现此问题。感谢您的帮助。
哔哔one
红糖糍粑
相关分类