【问题标题】:How to add items in a recycler view from a different class如何在不同类的回收站视图中添加项目
【发布时间】:2020-04-02 14:08:48
【问题描述】:

在我的通知片段上实现了一个回收器视图,在相同的片段上添加项目没有问题,但是当我尝试从另一个片段添加项目时,它抛出并错误 JavaNullPointException。

这是我的具有回收站视图的片段

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






        notimodels = new ArrayList<> ();

        mRecyclerView = v.findViewById(R.id.notificationsRecycler);


        fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");

        // get data from the notificiation
        return  v;
    }




    @Override
    public void onStart() {
        super.onStart ();
        swipeRefreshLayout.setRefreshing(true);
        fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
    }



   public void fillNotification(int mImage, String mtext, String mtext2, String mDate)
    {
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager (getContext ());
        mAdapter = new NotificationAdapter (notimodels);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        notimodels.add (0,new NotificationModel (mImage,mtext,mtext2,mDate));
    }
}

**当我尝试从其他片段(例如 tis)调用函数时“”

NotificationFragmentCict notificationFragmentCict =new NotificationFragmentCict ();
        notificationFragmentCict.fillNotification (R.drawable.bursar, "Bursar", "your clreard","min");

我的应用程序崩溃并抛出此错误

Process: com.univibezstudios.ocappservice.ocapp, PID: 3380
    java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference

问题是这个 显示此错误是因为您的片段视图尚未创建。这就是为什么 recyclerview 为 null 并且您在 null recyclerview 上调用 setHasFixedSize(...) 方法的原因。但我无法解决它任何帮助家伙

【问题讨论】:

  • 当你这样创建一个新的fragment时:“new NotificationFragmentCict()”,onCreateView方法没有被调用,因为布局没有被膨胀,所以没有recycler view。 (尝试在 onCreateView 中放置一个断点,看看它是否在初始化之后被调用)。您需要使用片段管理器在某处为片段充气

标签: android android-fragments android-recyclerview


【解决方案1】:

你需要初始化你在函数fillNotification之外的回收器视图:

mRecyclerView = v.findViewById(R.id.notificationsRecycler);

您还需要第二个片段中的 ArrayList:

  notimodels = new ArrayList<> ();

【讨论】:

  • 非常感谢,但问题是如何从 v.findviewbyId 中初始化回收器不能用于我在 create 之外的函数
  • 你可以从任何地方调用findViewById,如果它是一个与其他fragment不同的recyclerview,你可以将它作为参数传递
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 2017-12-13
  • 2018-02-25
相关资源
最近更新 更多