我试图从firebase中恢复四张照片,并将它们显示在幻灯片中,并使用getUrl()
来检索URL。
但是,setSliderViews()
方法无法执行,并且我看到此错误:
致命异常:main:”
如何解决此问题?
public class MainActivity extends AppCompatActivity {
Upload data;
ArrayList<String> url = new ArrayList<String>();
SliderLayout sliderLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sliderLayout = findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(SliderLayout.Animations.FILL); //set indicator animation by using SliderLayout.Animations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
sliderLayout.setScrollTimeInSec(1); //set scroll delay in seconds :
getUrl();
setSliderViews();
}
private void getUrl(){
final ArrayList<String> mUrl = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("upload").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
data = snapshot.getValue(Upload.class);
if (data != null) {
mUrl.add(data.getImageUrl());
}
}
url = mUrl;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void setSliderViews() {
for (int i = 0; i <= 3; i++) {
SliderView sliderView = new SliderView(this);
switch (i) {
case 0:
sliderView.setImageUrl(url.get(0));
break;
case 1:
sliderView.setImageUrl(url.get(1));
break;
case 2:
sliderView.setImageUrl(url.get(2));
break;
case 3:
sliderView.setImageUrl(url.get(3));
break;
}
sliderView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
//sliderView.setDescription(" " + (i + 1));
final int finalI = i;
sliderView.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
@Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(MainActivity.this, "This is slider " + (finalI + 1), Toast.LENGTH_SHORT).show();
}
});
//at last add this view in your layout :
sliderLayout.addSliderView(sliderView);
}
}
}
答案 0 :(得分:1)
addListenerForSingleValueEvent
不会立即执行,因此在您的setSliderViews()
被称为'url'ArrayList时是空的。您需要等待侦听器执行。