开发者

Problem with converting a string to an integer and passing as an ID to a view

There are 20 buttons in an Activity .

The ids are R.id.ButtonR1C1; R.id.ButtonR1C2 .. and so on ie. Row 1, Col 1..

now earlier I had created 20 buttons.

private Button b1,b2,b3...;

and then

b1=(Button)findViewbyId(R.id.ButtonR1C1);
b2=(Button)findViewbyId(R.id.ButtonR1C2);

.... and so on.

Finally

b1.setOnClickListener(this);
b2.setOnClickListener(this);  

... 20

so I thought I'd create a Button Array

Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
   开发者_开发百科for (int j=1;j<=5;j++) {
      String t="R.id.ButtonR"+i+"C"+j;
      barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
   }
}

Gives an error..

Any help??


If you have copied your code directly, your syntax is wrong.

Button barray[][]=new Button{4][5];

should be

Button barray[][]=new Button[4][5];

Note the curly bracket instead of square bracket before the 4.

Your next problem, is that you are trying to get the value of R.id.something, but you only have the string representation of it. So, the only way I know to do this is using reflection.

What you need to do is,

Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
   for (int j=1;j<=5;j++) {
      Class rId = R.id.getClass();
      // this gets the id from the R.id object.
      int id = rId.getField("ButtonR"+i+"C"+j).getInt(R.id);
      barray[i-1][j-1]=(Button)findViewbyId(id);
   }
}


String t="R.id.ButtonR"+i+"C"+j;
Integer.parseInt(t);

This part of your code will definitly throw a runtime exception, because t does not contain a numeric value.

I don't know the format/value of your ID values, but this might work:

Button barray[][]=new Button[4][5];      // type corrected
for(int i=1; i<4; i++) {                   // changed the for loop...
   for (int j=1; j<5; j++) {               // changed the for loop...
      String t="R.id.ButtonR"+i+"C"+j;
      barray[i-1][j-1]=(Button)findViewbyId(t);  // t *is* the id (?)
   }
}


The Problem is here:

String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));

You're trying to convert a String t to an Integer (while the String is not numeric at all). This will result in NumberFormatException. You should make sure that t is absolutely numeric.


I used this code:

Class c = Class.forName("com.test.R$id");
Integer i = new Integer(c.getField("ToolsbuttonR3C4").getInt(new R.id()));
System.out.println("HEXA="+i.toHexString(i));

and the ids are in sequential order. so it can be done.

Thanks ppl


So you are trying to convert the String "R.id.ButtonR1C1" to a NUMBER...

That will most certainly give you a NumberFormatException since it is CLEARLY NOT A NUMBER! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜