错误代码是
E / Android运行时:致命异常:主要 工艺:kr.coin.stylepicker,PID:7673 java.lang.NullPointerException:尝试调用虚拟方法'void kr.coin.stylepicker.adapter.MainListAdapter.notifyDataSetChanged()'on 空对象引用 在kr.coin.stylepicker.fragmain.Frag_MainList.onResume(Frag_MainList.java:296) 在kr.coin.stylepicker.activity.MainActivity $ 2.onPageSelected(MainActivity.java:240)
我不会详细解释代码。
只需在片段的mainRV_Adapter.notifyDataSetChanged ()
上使用onResume
让我知道您是否收到NullPointerException
或如何解决
MainActivity.java
public class MainActivity extends AppCompatActivity{
Fragmant1 mainList;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainList = new Frag_MainList();
mViewPager = findViewById(R.id.viewpager);
cut;
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
switch (position){
case 0:
otherfrag.onResume();
break;
case 1:
mainList.onResume(); <- here (MainActivity.java:240)
break;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
Fragment1.java
public class Frag_MainList extends Fragment {
RecyclerView mainRecyclerView;
MainListAdapter mainRV_Adapter;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
mainRecyclerView = view.findViewById(R.id.my_listview);
mainRV_LayoutManager = new LinearLayoutManager(getActivity());
mainRV_Adapter = new MainListAdapter(context, tagListData);
mainRecyclerView.setLayoutManager(mainRV_LayoutManager);
mainRecyclerView.setAdapter(mainRV_Adapter);
mainRV_Adapter.notifyDataSetChanged();
}
@Override
public void onResume() {
super.onResume();
(RecyclerView)getView().findViewById(R.id.my_listview);
mainRV_Adapter.notifyDataSetChanged(); <- Here NullPointerException (Frag_MainList.java:296)
}
}
为什么它是NullPointerException?
缺少什么?
让我知道在这种情况下如何防止NullPointerException。