4

I have an app that creates controls programmatically according to information coming from a database.

In the application I need to reference a dynamically created Layout, so that I need to assign it an ID.

Currently, I have:

    final Random random = new Random();
    for (int i = 0; i < count; i++) {
        TdcItem item = items[i];

        int id = item.getID();
        final int layoutId = random.nextInt(id * (id + 1));

        ....
    }

Where id variable is an ID coming from the database, which of course is unique in database table.

The problem is that I am also creating buttons coming from another table, so, the ID's are unique from that table point of view, however, some of them are not unique in activity context.

That cause that when I use findViewById trying to find a layout, a button is found instead, throwing an invalid cast exception.

Is there a way to create unique ID's for the layouts?

Thanks Jaime

jstuardo
  • 3,901
  • 14
  • 61
  • 136

2 Answers2

4

The Android API provides a method in the View class that does this for you if you're using API 17 or higher:

View.generateViewId();

According to the API:

Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.

star4z
  • 377
  • 3
  • 10
  • Yes but the user doesn't have any control over what the generated ID is going to be. Is there instead a way to start with a human readable String ID and use a method to convert that to an integer suitable for setId? The method would have to output the same int given the same string – Samwise Ganges Jul 19 '23 at 20:04
1

Convert the memory address of View's object to int and set that as the view's id. It will always be unique in the Activity's context.

for (int i = 0; i < count; i++) {
        TdcItem item = items[i];

        int id = Integer.parseInt(""+item, 16);
        item.setId(id);
        ....
    }
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • does not compile: no suitable method found for parseInt(TdcItem, int). Method Integer.parseInt(String.int) is not applicable – jstuardo Oct 21 '15 at 16:39
  • The code is just a proof of concept mentioned above. You can fix these minors things yourself too. Anyways try the modified code. – Umer Farooq Oct 21 '15 at 16:47