在发帖之前,我花了相当多的时间自己弄清楚,不过我已经删除了各种错误。我正在开发一个小笔记应用程序,在我的应用程序中使用包含回收视图的片段之前,一切都很好。问题是我无法将从数据库检索到的数据传递给回收视图适配器。错误显示“尝试在空对象引用上调用虚方法‘void com.example.diary.RecyclerAdapter.setdata(java.util.List)’”我已验证数据不为空,我很困惑为什么我会收到空指针错误。相关代码贴在下面。fragment.java @Overridepublic 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;}如果我不使用片段,则不会出现此问题。感谢您的帮助。
2 回答
哔哔one
TA贡献1854条经验 获得超8个赞
您需要retrievetasks()
在初始化适配器后调用方法。这是导致问题的原因
adapter = new RecyclerAdapter(numofitems); retrievetasks();
红糖糍粑
TA贡献1815条经验 获得超6个赞
in adapteryourretrieveTasks与您初始化的不同。您正在初始化一个本地实例,该实例超出了您的方法范围retrieveTasks。大概你在片段中有一个属性adapter已经命名,所以你可以只删除本地实例来初始化正确的:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_recents, container, false);
RecyclerAdapter adapter; // <- DELETE THIS
db = NotesDatabase.createdb(getContext());
adapter = new RecyclerAdapter(numofitems);
}
希望有帮助!
添加回答
举报
0/150
提交
取消