1

i will like to use variable cb in findViewById as below, but it is giving me an error, any ideas how to do it

public class Compare1 extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.commac1);
    // setdesign();
    ImageView btn=(ImageView) findViewById(R.id.comparenow);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            for(int check=1;check<17;check++){
                int a=check;
            String cb="checkBox"+a;
               int id=getResources().getIdentifier(cb, "id", getPackageName());
                CheckBox cb=(CheckBox) findViewById(id);
                if(cb.isChecked()){
                    Toast.makeText(Compare1.this, "you selected" +cb, Toast.LENGTH_SHORT).show();
                    }}

        }
    });
5
  • why are you not giving the resource id like you did with the imageview? Commented Apr 3, 2014 at 20:30
  • @tyczj because there are 16 checkboxes, it will be very messy Commented Apr 3, 2014 at 20:31
  • because he have 17. what is the error you are getting? Commented Apr 3, 2014 at 20:31
  • i am checking on my device and the application is stopping after i click on imageview. if i remove the for loop and hardcode the cb variable as cb1,cb2... it is working fine Commented Apr 3, 2014 at 20:34
  • Please post the logcat output of the error you receiving. Commented Apr 3, 2014 at 21:08

1 Answer 1

1

try:

int id= Compare1.this.getResources().getIdentifier(cb, "id", getPackageName());

using getResources() alone makes this method exist in the OnClickListener object.

Also:

(CheckBox) Compare1.this.findViewById(id);
Sign up to request clarification or add additional context in comments.

1 Comment

@ hasan if i remove the for loop and hardcode the cb variable as cb1,cb2... it is working fine. no issues with this line.issue is with this line CheckBox cb=(CheckBox) findViewById(id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.