无法将数据从RecyclerView适配器传递到Viewpager适配器

时间:2019-04-18 06:05:59

标签: android-recyclerview android-viewpager

我正在创建一个简单的图库应用程序,其中的图像显示在RecyclerView内的MainActivity上,然后单击任何图像,它将带我们进入SlideActivity,在其中我要在ViewPager上显示图像,然后滑动所有图像应显示在ViewPager。为了检索图像,我正在使用Glide。图像在RecyclerView上加载完全正常,但是当我单击任何图像时,都会收到此异常“ java.lang.ArrayIndexOutOfBoundsException:length = 15; index = -1”。 我知道有很多类似的问题,我看到了所有代码,但不明白,所以最终决定问一个问题,我粘贴代码到现在为止。任何建议或建议都将是有益的,因为我一个人工作,没有导师,正在学习。谢谢!

错误:

java.lang.ArrayIndexOutOfBoundsException: length=15; index=-1
        at java.util.ArrayList.get(ArrayList.java:439)
        at com.starmoonsolutions.imagegallery.RecycleViewAdapter$ViewHolder$1.onClick(RecycleViewAdapter.java:63)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24697)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

ImageUrl.java

public class ImageUrl {
    String imageUrl;

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

MainActivity:

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    RecyclerView recyclerView;
    GridLayoutManager gridLayoutManager;
    ArrayList<ImageUrl> imageUrlList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        recyclerView = findViewById(R.id.recyclerView);
        gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);

        imageUrlList = prepareData();
        RecycleViewAdapter galleryAdapter = new RecycleViewAdapter(getApplicationContext(), imageUrlList);
        recyclerView.setAdapter(galleryAdapter);
    }
    private ArrayList prepareData(){
        // here you should give your image URLs and that can be a link from the Internet
        String imageUrls[] = {
                "https://images.pexels.com/photos/358457/pexels-photo-358457.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
                "https://images.pexels.com/photos/934964/pexels-photo-934964.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/1202887/pexels-photo-1202887.jpeg?auto=compress&cs=tinysrgb&h=650&w=940",
                "https://images.pexels.com/photos/337909/pexels-photo-337909.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/894443/pexels-photo-894443.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/951325/pexels-photo-951325.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/1534411/pexels-photo-1534411.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/266436/pexels-photo-266436.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/1894350/pexels-photo-1894350.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/87009/earth-soil-creep-moon-lunar-surface-87009.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/1820563/pexels-photo-1820563.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                "https://images.pexels.com/photos/1274260/pexels-photo-1274260.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
        };
        imageUrlList = new ArrayList<>();
        for (int i = 0; i < imageUrls.length; i++) {
            ImageUrl imageUrl = new ImageUrl();
            imageUrl.setImageUrl(imageUrls[i]);
            imageUrlList.add(imageUrl);
        }
        Log.d("MainActivity", "List count: " + imageUrlList.size());
        return  imageUrlList;
    }
}

RecyclerViewAdapter:

    public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder>{

        private ArrayList<ImageUrl> imageUrls;
        private Context context;

        public RecycleViewAdapter(Context context, ArrayList<ImageUrl> imageUrls) {
            this.imageUrls = imageUrls;
            this.context = context;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_layout, viewGroup, false);
            return new ViewHolder(view);
        }

        /**
         * gets the image url from adapter and passes to Glide API to load the image
         *
         * @param viewHolder
         * @param i
         */
        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
            Glide.with(context).load(imageUrls.get(i).getImageUrl()).into(viewHolder.img);
        }

        @Override
        public int getItemCount() {
            return imageUrls.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder{

            RecyclerView recyclerView;
            ImageView img;

            public ViewHolder(@NonNull final View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.imageView);
                recyclerView = itemView.findViewById(R.id.recyclerView);
                final int pos = getAdapterPosition();
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, SlideActivity.class);
error point here->      intent.putExtra("image", String.valueOf(imageUrls.get(pos).getImageUrl())); <- error point here 
                        intent.putExtra("position", pos);
                        intent.putExtra("list", imageUrls.get(pos).imageUrl);
                        context.startActivity(intent);
                    }
                });
            }
        }
    }

SlideActivity(ViewPager):

public class SlideActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private Context context = SlideActivity.this;
    private ViewPagerAdapter adapter;
    private ArrayList<String> list;
    String image;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_activity);

        viewPager = findViewById(R.id.viewPager);
        getIntentInfo();

        adapter = new ViewPagerAdapter(list,context);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem((position));
    }

    private void getIntentInfo() {
        image = getIntent().getStringExtra("image");
        list  = getIntent().getStringArrayListExtra("list");
        position = getIntent().getIntExtra("position",0);
    }
}

ViewPagerAdapter:

public class ViewPagerAdapter extends PagerAdapter {
    private ArrayList<String> imageUrls;
    private android.content.Context context;
    private LayoutInflater inflater;
    private ImageView wallpaper;

    public ViewPagerAdapter() {

    }

    public ViewPagerAdapter(ArrayList<String> imageUrls, android.content.Context context) {
        this.imageUrls = imageUrls;
        this.context = context;
    }

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

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view.equals(o);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull final ViewGroup container, final int position) {

        inflater = LayoutInflater.from(container.getContext());
        View view = inflater.inflate(R.layout.pager_item, container, false);
        wallpaper = view.findViewById(R.id.walpaperImage);
        Glide.with(context).asBitmap().load(imageUrls.get(position)).into(wallpaper);
        container.addView(view, 0);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}

1 个答案:

答案 0 :(得分:0)

问题实际上出在适配器位置上。

x, y = np.random.rand(2, 20)

ax = sns.regplot(x, y, line_kws={'label': 'Regression line'})
ax.collections[1].set_label('Confidence interval')
ax.legend()

由于ViewHolder被回收,适配器的位置可以更改,因此您需要在点击侦听器中获取最新的适配器位置。

关于Bundle数据,传递“ String”类型的URL列表而不是自定义对象,

public ViewHolder(@NonNull final View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.imageView);
                recyclerView = itemView.findViewById(R.id.recyclerView);

                // remove the below line
                //final int pos = getAdapterPosition();

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, SlideActivity.class);

                        // you need to freshly get the adapter position here.
                        int pos = getAdapterPosition();

error point here->      intent.putExtra("image", String.valueOf(imageUrls.get(pos).getImageUrl())); <- error point here 
                        intent.putExtra("position", pos);
                        intent.putExtra("list", imageUrls.get(pos).imageUrl);
                        context.startActivity(intent);
                    }
                });
            }

或使用Parcelable library序列化自定义对象。