我正在使用viewpager使用滑块,并且该滑块显示一些图像。我将此图像存储在我的Firebase数据库中,但是此应用程序被挤压,并在addValueEventListener方法中显示错误。
MainActivity.java
sliderpager = findViewById(R.id.slider);
lstSlides = new ArrayList<SliderModel>();
SliderPageAdapter sliderPageAdapter = new SliderPageAdapter(MainActivity.this,lstSlides);
sliderPageAdapter.notifyDataSetChanged();
sliderpager.setAdapter(sliderPageAdapter);
database = FirebaseDatabase.getInstance();
reference = database.getReference("Image");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot img : dataSnapshot.getChildren()){
SliderModel sm = img.getValue(SliderModel.class);
lstSlides.add(sm);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
SliderPageAdapter.java
private Context ctx;
List<SliderModel> SliderModels;
public SliderPageAdapter(Context ctx, List<SliderModel> SliderModels) {
this.ctx = ctx;
this.SliderModels = SliderModels;
}
@Override
public int getCount() {
return SliderModels.size();
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View slideLayout = inflater.inflate(R.layout.slider_row,null);
ImageView slideImg = slideLayout.findViewById(R.id.sliderimg);
Picasso.get().load(SliderModels.get(position).getImage()).into(slideImg);
container.addView(slideLayout);
return slideLayout;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
super.destroyItem(container, position, object);
container.removeView((View)object);
}
SliderModel.java
private String image;
public SliderModel() {
}
public SliderModel(String image) {
this.image = image;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
如何解决此错误?
答案 0 :(得分:0)
您需要删除for循环,因为在进行迭代时,要检索的数据的类型为String
。因此,请执行以下操作:
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
SliderModel sm = dataSnapshot.getValue(SliderModel.class);
lstSlides.add(sm);
}
}