This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


在8个月前关闭。




我在我的项目中使用view-pager实现了图像滑块。现在我想在单击滑块的特定图像时使用。它将打开一个新的细节片段。根据该图像滑块的可用信息。因此,我尝试通过使用setOnClickListner获取图像位置来实现界面。但是现在的问题是,单击图像时出现异常。我的应用崩溃了下面是我的代码...

滑块图像适配器:
public class SliderImageAdapter extends SliderViewAdapter<SliderImageAdapter.SliderAdapterVH>{

    public List<Banner> bannerList;
    public Context context;
    private OnItemClicked onClick;

    public interface OnItemClicked {
        void onItemClick(int position);
    }

    public SliderImageAdapter(Context context, List<Banner> bannerList) {

        this.bannerList = bannerList;
        this.context = context;
    }

    @Override
    public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_myshop, parent, false);
        return new SliderAdapterVH(inflate);
    }

    @Override
    public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {

        Glide.with(viewHolder.itemView)
                .load(bannerList.get(position).getmSliderImage())
                .fitCenter()
                .into(viewHolder.imageViewBackground);

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onClick.onItemClick(position);
            }
        });
    }

    @Override
    public int getCount() {
        return bannerList.size();
    }

    public int getItemPosition (Object object) {
        return POSITION_NONE;
    }

    public void setOnClick(OnItemClicked onClick) {
        this.onClick = onClick;
    }



    class SliderAdapterVH extends SliderViewAdapter.ViewHolder {

        View itemView;
        ImageView imageViewBackground;
        ImageView imageGifContainer;

        public SliderAdapterVH(View itemView) {
            super(itemView);
            imageViewBackground = itemView.findViewById(R.id.iv_auto_image_slider);
            imageGifContainer = itemView.findViewById(R.id.iv_gif_container);
            this.itemView = itemView;
        }
    }
}

在这里,我在图像滑块适配器中得到了异常:java.lang.NullPointerException:尝试在空对象引用上调用接口方法SliderImageAdapter $ OnItemClicked.onItemClick(int)'。
@Override
    public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {

        Glide.with(viewHolder.itemView)
                .load(bannerList.get(position).getmSliderImage())
                .fitCenter()
                .into(viewHolder.imageViewBackground);

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onClick.onItemClick(position);
            }
        });
    }

主页片段代码:
public class HomeFragment extends Fragment implements SliderImageAdapter.OnItemClicked {

private SliderImageAdapter sliderImageAdapter;
    private List<Banner> bannerList;

bannerList = new ArrayList<>();
        sliderImageAdapter = new SliderImageAdapter(getActivity(), bannerList);

sliderMyshop = view.findViewById(R.id.imageSlider);
        sliderMyshop.setSliderAdapter(sliderImageAdapter);
        sliderMyshop.setIndicatorAnimation(IndicatorAnimations.WORM); //set indicator animation by using SliderLayout.IndicatorAnimations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
        sliderMyshop.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
        sliderMyshop.setIndicatorSelectedColor(Color.WHITE);
        sliderMyshop.setIndicatorUnselectedColor(Color.GRAY);
        sliderMyshop.startAutoCycle();

mFirestore.collection("Banner").orderBy("mSliderImage", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable QuerySnapshot documentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.d(TAG, "Error : " + e.getMessage());
                }
                assert documentSnapshots != null;

                for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {

                    if (doc.getType() == DocumentChange.Type.ADDED) {
                        String doc_id = doc.getDocument().getId();
                        Banner banner = doc.getDocument().toObject(Banner.class).withDocId(doc_id);
                        bannerList.add(doc.getNewIndex(), banner);
                        sliderImageAdapter.notifyDataSetChanged();

                    } else if (doc.getType() == DocumentChange.Type.MODIFIED) {
                        String docID = doc.getDocument().getId();
                        Banner changedModel = doc.getDocument().toObject(Banner.class).withDocId(docID);
                        if (doc.getOldIndex() == doc.getNewIndex()) {
                            // Item changed but remained in same position
                            bannerList.set(doc.getOldIndex(), changedModel);
                        } else {
                            // Item changed and changed position
                            bannerList.remove(doc.getOldIndex());
                            bannerList.add(doc.getNewIndex(), changedModel);
                        }
                    } else if (doc.getType() == DocumentChange.Type.REMOVED) {
                        // remove
                        bannerList.remove(doc.getOldIndex());
                    }
                    sliderImageAdapter.notifyDataSetChanged();
                }
            }
        });

@Override
    public void onItemClick(int position) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragment_container_dashboard, SliderClickFragment.newInstance(bannerList.get(position).getmSliderImage()));
        ft.addToBackStack(null);  // this line responsible for adding fragment in backstack.
        ft.commit();
    }

详细片段代码:
public abstract class SliderClickFragment extends Fragment {

public static Fragment newInstance(String getmSliderImage) {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.slider_click_listner, container, false);
        return view;
    }
}

最佳答案

因此,问题可能是您在没有OnItemClicked.onClick实例的情况下调用OnItemClicked
快速浏览

private OnItemClicked onClick;

public interface OnItemClicked {
    void onItemClick(int position);
}

public SliderImageAdapter(Context context, List<Banner> bannerList) {

    this.bannerList = bannerList;
    this.context = context;
}

然后在这里使用
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onClick.onItemClick(position);
        }
    });

您正在尝试在OnClicknull实例上调用OnItemClicked方法。
一种方法是将OnItemClicked onclick作为参数添加到构造函数,然后使片段实现OnItemClicked接口。
这样的事情。
private OnItemClicked onClick;

public interface OnItemClicked {
  void onItemClick(int position);
}

public SliderImageAdapter(Context context, List<Banner> bannerList,
    OnItemClicked onClick) {

   this.bannerList = bannerList;
   this.onClick = onClick;
   this.context = context;
}

然后在HomeFragment
public class HomeFragment extends Fragment implements
SliderImageAdapter.OnItemClicked{
   private SliderImageAdapter sliderImageAdapter
   = new SliderImageAdapter(getActivity(), bannerList, this);
}

08-03 14:35