RecyclerView中的onClickListener有问题

时间:2019-04-24 07:38:14

标签: java android android-recyclerview

我刚刚添加了一个意图,以便我可以单击“回收者”视图中存在的项目之一,然后转到下一页,但是我在那儿遇到了错误,还添加了一条Toast消息单击该项目后,效果很好,但意图使该应用程序崩溃。而且我还在适配器的主要活动中添加了此代码。需要帮助,谢谢

public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof ItemViewHolder) {
            final Notifications notification = notifications.get(position);
            final ItemViewHolder viewHolder = (ItemViewHolder) holder;
            viewHolder.title.setText(notifications.get(position).getTitle());
            viewHolder.description.setText(notifications.get(position).getDescription());
            viewHolder.date.setText(notifications.get(position).getDate());
            viewHolder.itemView.setBackgroundColor(Color.GRAY);

            viewHolder.notificationLay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText((firebaseMain)activity, "Item clicked " + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(firebaseMainActivity, NotificationDetails.class);
                    context.startActivity(intent);
                }
            });
        } else if (holder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }

    }
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.app.sample.collegeautomation, PID: 1875
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ComponentName.<init>(ComponentName.java:130)
        at android.content.Intent.<init>(Intent.java:6082)
        at com.app.sample.collegeautomation.firebaseNotifications.firebaseListViewAdapter$3.onClick(firebaseListViewAdapter.java:146)
        at android.view.View.performClick(View.java:6597)
        at com.balysv.materialripple.MaterialRippleLayout$PerformClickEvent.run(MaterialRippleLayout.java:648)
        at com.balysv.materialripple.MaterialRippleLayout$3.onAnimationEnd(MaterialRippleLayout.java:336)
        at android.animation.Animator$AnimatorListener.onAnimationEnd(Animator.java:552)
        at android.animation.AnimatorSet.endAnimation(AnimatorSet.java:1294)
        at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1079)
        at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)

1 个答案:

答案 0 :(得分:1)

**create the constrtuctor of the adapter class and pass context**

public UserListAdapter(Context context, int resource,List<UserListDataModel> objects) {
    super(context, resource, objects);
    this.ctx = context;
}
**now in Intent pass this ctx**

Intent intent = new Intent(ctx,AlarmDispositonActivity.class);
    intent.putExtras(bundle);