Darrellii
Darrellii

Reputation: 47

how to find view by id using a string variable?

I'm writing an android app and I'm trying to initialize a grid of buttons in with a nested loop.

i originally found this current solution through research but i cant figure out whats going wrong.

for (int i = 0; i < piles.length; i++)
  for (int j = 0; j < piles[0].length; j++) {

        id = getResources().getIdentifier("R.id." + "b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id","app.dj");
        bpiles[i][j] = ((Button) this.findViewById(id));
        bpiles[i][j].setOnClickListener(this);
   }
 }

for some reason when id is always set to 0 and thus bpiles[0][0] is set to null, and then get a null pointer exception.

i'v tried allot of little solutions but nothing has worked.

does anyone either see what my problem is or have a better solution to this.

oh, and i came up with this when i saw this post. Android findViewbyId with a variant string

Upvotes: 2

Views: 2967

Answers (3)

Sam
Sam

Reputation: 86958

It looks like the first parameter of getIdentifier() is wrong:

id = getResources().getIdentifier("R.id." + "b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id","app.dj");
//             Do not use "R.id." ^^^^^^^

We already know that you are trying to reference R and the second parameter specifies the type "id". Change it too:

id = getResources().getIdentifier("b" + numplayaz + Integer.toString(i) + Integer.toString(j), "id", "app.dj");

Also String's + operator should take precedence, so you can "b" + numplayaz + i + j. But a StringBuilder might be your fastest approach and easier to read.

Upvotes: 3

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

Once you build your drawable name, you can use this function to get its Id:

public static int getDrawableByName( String name ) {
    int drawableId = 0;

    try {
         Class res = R.drawable.class;
         Field field = res.getField( name );
         drawableId = field.getInt(null);
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return drawableId;
}

Upvotes: 0

ixx
ixx

Reputation: 32269

0 means that the id is not found.

  1. Have you checked that all the ids you are referencing exist?

  2. Use getPackageName() instead of "app.dj". Maybe it's incomplete.

Upvotes: 0

Related Questions