亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的片段不能顯示來自 recyclerview 的數據?

為什么我的片段不能顯示來自 recyclerview 的數據?

Cats萌萌 2023-05-17 14:35:15
在發帖之前,我花了相當多的時間自己弄清楚,不過我已經刪除了各種錯誤。我正在開發一個小筆記應用程序,在我的應用程序中使用包含回收視圖的片段之前,一切都很好。問題是我無法將從數據庫檢索到的數據傳遞給回收視圖適配器。錯誤顯示“嘗試在空對象引用上調用虛方法‘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();


查看完整回答
反對 回復 2023-05-17
?
紅糖糍粑

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);

}

希望有幫助!


查看完整回答
反對 回復 2023-05-17
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號