catch(NotFoundException e)对我的情况不起作用

时间:2015-01-30 16:07:42

标签: android image try-catch

我的应用程序一个接一个地显示图像的图像名称是a1,a2,a3 ...... an,我试图在图像数量持续时捕获异常,但它对我不起作用。 这是代码:

imagename = getIntent().getExtras().getString("somekey");

    resId = getResources().getIdentifier(imagename + num, "drawable",
            getPackageName());

    try {
        i10.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                image1.setImageResource(resId);
                num++;
                overridePendingTransition(R.anim.pushin, R.anim.pushout);

            }
        });
    } catch (NotFoundException e){
        e.printStackTrace();
        i10.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), Menu.class);
                startActivity(i);
                overridePendingTransition(R.anim.pushinhorizontal,
                        R.anim.pushouthorizontal);

            }
        });
    }

1 个答案:

答案 0 :(得分:0)

你的try块正在处理侦听器的赋值,而不是获取资源标识符

你应该这样做

imagename = getIntent().getExtras().getString("somekey");

i10.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        int resID = 0;
        try{
            resId = getApplicationContext().getResources().getIdentifier(imagename + num, "drawable", getPackageName());
        }catch (NotFoundException e){
            e.printStackTrace();
        }
        if(resId > 0){
            image1.setImageResource(resId);
            num++;
            overridePendingTransition(R.anim.pushin, R.anim.pushout);
        }
        else{
            Intent i = new Intent(getApplicationContext(), Menu.class);
            startActivity(i);
            overridePendingTransition(R.anim.pushinhorizontal,
                    R.anim.pushouthorizontal); 
        }
    }
});