在發(fā)帖之前,我花了相當多的時間自己弄清楚,不過我已經(jīng)刪除了各種錯誤。我正在開發(fā)一個小筆記應(yīng)用程序,在我的應(yīng)用程序中使用包含回收視圖的片段之前,一切都很好。問題是我無法將從數(shù)據(jù)庫檢索到的數(shù)據(jù)傳遞給回收視圖適配器。錯誤顯示“嘗試在空對象引用上調(diào)用虛方法‘void com.example.diary.RecyclerAdapter.setdata(java.util.List)’”我已驗證數(shù)據(jù)不為空,我很困惑為什么我會收到空指針錯誤。相關(guān)代碼貼在下面。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); //這是錯誤發(fā)生的地方'adapter.java public void setdata(List<NotesEntry> notesEntries) { try { notesEntryList = notesEntries; notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); }}public List<NotesEntry> getnotesentries() { return notesEntryList;}如果我不使用片段,則不會出現(xiàn)此問題。感謝您的幫助。
2 回答

嗶嗶one
TA貢獻1854條經(jīng)驗 獲得超8個贊
您需要retrievetasks()
在初始化適配器后調(diào)用方法。這是導致問題的原因
adapter = new RecyclerAdapter(numofitems); retrievetasks();

紅糖糍粑
TA貢獻1815條經(jīng)驗 獲得超6個贊
in adapteryourretrieveTasks與您初始化的不同。您正在初始化一個本地實例,該實例超出了您的方法范圍retrieveTasks。大概你在片段中有一個屬性adapter已經(jīng)命名,所以你可以只刪除本地實例來初始化正確的:
@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
提交
取消