android-fragments getContext()在调用更新RecyclerView函数时使我的应用程序崩溃?

pb3s4cty  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(136)

我的应用程序总是崩溃,当我想访问一个特定的片段。错误是:
致命异常错误:主要流程:幼儿园,PID:15680错误代码:尝试在一个空的对象引用上调用虚拟方法“void androidx.recyclerview.widget. recyclerView.setLayoutManager(androidx.recyclerview.widget. recyclerView$LayoutManager)”,该对象引用位于以下位置:
我看到很多人在过去都有类似的问题,但没有想法或建议帮助我解决我的。
我尝试使用 getContext()onAttach()GroupbookKrippeFragment.this.getContext() 和其他一些方法来获取上下文。

更新开始(12.11.22)

我可以把问题缩小一点。应用程序很稳定,工作正常,直到我做了以下更改:
1.)为了使用来自数据库的recyclerview条目更新tableList,我将以下代码封装到GroupbookKrippeFragment.java中的一个新方法中:

public void setRecyclerView(List<ChildrenTable> childrenTableList) {
        recycler_view.setLayoutManager(new LinearLayoutManager(getContext()));
        childAdapter = new ChildAdapter(getContext(), childrenTableList);
//        childAdapter = new ChildAdapter(getContext());
        recycler_view.setAdapter(childAdapter);
    }

2.)我在我的DatabaseHelper.java类中对 AllChildren 的onPostExecute()异步任务调用了此方法:

public class DatabaseHelper {
Context context;
GroupbookKrippeFragment groupbookKrippeFragment = new GroupbookKrippeFragment();

public DatabaseHelper(Context context) {
    this.context = context;
}

public static DatabaseHelper getInstance(Context context) {
    return new DatabaseHelper(context);
}

// Insert Data
// TODO: Add all columns as Input parameter for Database
public void addNewChild(
        String child_name, String child_surname, String child_birthday,
        String child_birthday_location, String child_confession, String child_nationality) {

    class NewChild extends AsyncTask<Void, Void, ChildrenTable> {

        @Override
        protected ChildrenTable doInBackground(Void... voids) {
            ChildrenTable childrenTable = new ChildrenTable();

            // TODO: Link all columns for Database
            childrenTable.setChild_name(child_name);
            childrenTable.setChild_surname(child_surname);
            childrenTable.setChild_birthday(child_birthday);
            childrenTable.setChild_birthday_location(child_birthday_location);
            childrenTable.setChild_confession(child_confession);
            childrenTable.setChild_nationality(child_nationality);

            DatabaseClient.getInstance(context)
                    .getChildrenDatabase()
                    .childrenDAO()
                    .insertData(childrenTable);
            return childrenTable;
        }

        @Override
        protected void onPostExecute(ChildrenTable childrenTable) {
            super.onPostExecute(childrenTable);
            if (childrenTable != null) {
                Toast.makeText(
                        context,
                        childrenTable.getChild_name() + "\n" +
                        childrenTable.getChild_surname(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    NewChild newChild = new NewChild();
    newChild.execute();
}

// Show all data from ChildrenTable
public void getAllChildrenData() {
    class AllChildren extends AsyncTask<Void, Void, List<ChildrenTable>> {

        @Override
        protected List<ChildrenTable> doInBackground(Void... voids) {
            List<ChildrenTable> list = DatabaseClient.getInstance(context)
                    .getChildrenDatabase()
                    .childrenDAO()
                    .selectAll();
            return list;
        }

        @Override
        protected void onPostExecute(List<ChildrenTable> childrenTable) {
            super.onPostExecute(childrenTable);
            if (childrenTable != null && childrenTable.size() > 0) {
                groupbookKrippeFragment.setRecyclerView(childrenTable);
            }

        }
    }

    AllChildren allChildren = new AllChildren();
    allChildren.execute();
}

}
每当我注解掉这个方法调用并将行从方法移到GroupbookKrippeFragment的onViewCreated中时,应用程序又恢复了稳定,但recyclerView数据没有显示,也没有随我的数据库更新。

更新结束(12.11.22)

非常感谢你的帮助提前-这里是我的文件:

群组书内容片段.java

public class GroupbookKrippeFragment extends Fragment {

Button addChildBtn;
RecyclerView recycler_view;
ChildAdapter childAdapter;
DatabaseHelper helper;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_groupbook_krippe, container, false);

    addChildBtn = view.findViewById(R.id.btn_groupBook_krippe_1);
    addChildBtn.setOnClickListener(view1 -> {
        Intent intent = new Intent(GroupbookKrippeFragment.this.getActivity(), GroupbookAddChildFragment.class);
        startActivity(intent);
    });

    recycler_view = view.findViewById(R.id.recycler_view);

    helper = DatabaseHelper.getInstance(getContext());
    helper.getAllChildrenData();

    return view;
}

public void setRecyclerView(List<ChildrenTable> childrenTableList) {
    recycler_view.setLayoutManager(new LinearLayoutManager(getContext()));
    childAdapter = new ChildAdapter(getContext(), childrenTableList);
    recycler_view.setAdapter(childAdapter);
  }
}

群组簿片段.java

public class GroupbookFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_groupbook, container, false);

    // Tab layout initialization
    TabLayout tabLayout = view.findViewById(R.id.tabLayout);
    ViewPager2 viewPager = view.findViewById(R.id.viewPager_groupBook);
    GroupbookAdapter adapterGroupBook = new GroupbookAdapter(getChildFragmentManager(), getLifecycle());
    viewPager.setAdapter(adapterGroupBook);

    // set 3 Tab titles
    tabLayout.addTab(tabLayout.newTab().setText("Krippe"));
    tabLayout.addTab(tabLayout.newTab().setText("Hafen"));
    tabLayout.addTab(tabLayout.newTab().setText("Kindergarten"));

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            tabLayout.selectTab(tabLayout.getTabAt(position));
        }
    });
    return view;
  }
}
lyfkaqu1

lyfkaqu11#

您的GroupbookKrippeFragment拥有DatabaseHelper。您的DatabaseHelper拥有GroupbookKrippeFragment的另一个示例,该示例未涉及片段事务,因此不会调用其生命周期方法(如onCreateView()),并且recycler_view在该示例中保持为空。
例如,您可以将对所属片段的引用作为构造函数参数传入,将其存储在一个字段中,并在以后对其调用setRecyclerView(),而不是将DatabaseHelper示例化new GroupbookKrippeFragment
这不是一个完美的设计,但可以帮助您在开发过程中向前迈进一步。

相关问题