我有一系列图像,当用户按下时应启动一个新活动并传递一些数据(自定义对象的ArrayList)。自定义对象的ArrayList根据用户输入进行初始化。现在,我面临的问题是,当用户尚未为ArrayList提供输入并单击任何Image时,它会显示应用程序停止。我尝试通过try和catch块来处理它,但它不起作用。当ArrayList不为空时,整个流程工作正常。Image to have look at App (on Top, series of images are there which gets populated basis user selection from a list and then user can click any image of them)
查找以下相关代码:
MainActivity的相关阻止:
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.imageView.setImageResource(horizontalList.get(position).imageId);
holder.txtview.setText(horizontalList.get(position).txt);
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String list = horizontalList.get(position).txt.toString();
List<Coupon> couponList = new ArrayList<>();
try {
for (Place place : allOffers) {
Coupon coupon = new Coupon(place.mPlace, place.mOffer, place.mImage, list);
couponList.add(coupon);
}
Toast.makeText(MainActivity.this, list, Toast.LENGTH_SHORT).show();
Intent intentCat = new Intent(MainActivity.this, CategoryOffersActivity.class);
intentCat.putExtra("Category", (Serializable) couponList);
startActivity(intentCat);
} catch(Exception e) {
Toast.makeText(MainActivity.this,"List is Empty",Toast.LENGTH_SHORT).show();
}
}
});
}
用户点击图片时启动的新活动:
public class CategoryOffersActivity extends AppCompatActivity implements PlaceAdapter.AdapterInterface,Serializable {
ListView catListView;
List<Place> catOffers = new ArrayList<Place>();
PlaceAdapter catPlaceAdapter;
Place [] catPlaces;
List <Coupon> listCoupon=new ArrayList<Coupon>();
TextView mHeader;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoryoffers);
catListView = (ListView) findViewById(R.id.catListView);
mHeader=(TextView)findViewById(R.id.categoryName);
if (getIntent() != null) {
listCoupon = (ArrayList<Coupon>) getIntent().getSerializableExtra("Category");
if (listCoupon != null) {
ArrayList<Place> placeList = new ArrayList<>();
for(Coupon coupon : listCoupon) {
Place place=new Place(coupon.mPlace,coupon.mOffer,coupon.mImage);
placeList.add(place);
}
catPlaces=placeList.toArray(new Place[placeList.size()]);
mHeader.setText(listCoupon.get(0).mItemClicked+" Coupon History");
catPlaceAdapter = new PlaceAdapter(CategoryOffersActivity.this, R.layout.row, catPlaces, this);
if (catListView != null) {
catListView.setAdapter(catPlaceAdapter);
}
}
}
}
@Override
public void buttonPressed() {
// some action
}
}
答案 0 :(得分:0)
if ((listCoupon != null)&&(listCoupon.size()>0))
同时检查数组大小