• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Loading resources with a variable

Woulou

Lurker
Jul 11, 2010
6
0
Hello,
I have a problem which is the following : I can't load a resources from a variable (which would contain the id or the name of the resource):
For instance if you do :
Code:
Button button = (button)findViewById (R.id.buttonNb12)
(With an XML containing a button with id "buttonNb12" of course ;))
It will work.

But if you have your Id in a String how can you do it ? The following method doesn't work :( :
Code:
String x = "buttonNb12"
Button button = (button)findViewById (R.id.(x))
or this ...

Code:
String x = "R.id.buttonNb12"
Button button = (button)findViewById(x))
Do you have a solution please ?
Thanks
 
There are a few different solutions. The best one will depend on how flexible you want it to be, and how many different IDs you want to deal with.

The most obvious solution: just compare strings, and assign the correct ID value to an int variable.

Code:
	  private int getIdFromString( String idStr )
	  {
		  int id = 0 ;

		  if( idStr.equals("R.id.button1") )
		  {
			  id = R.id.button1 ;
		  }
		  else
		  if( idStr.equals("R.id.button2") )
		  {
			  id = R.id.button2 ;
		  }
		  else
		  . . . etc . . .

		  return id ;
	  }

	  private void something()
	  { 
		  String x = "R.id.buttonNb12" ;

		  int id = getIdFromString(x) ;
		  Button button = (button)findViewById(id) ;
	   
		  . . . etc . . .
	  }


If you have lots of IDs then it might be cumbersome to have a very long set of if statements.

You could set up all the IDs in a Map, and then use the string to look up the ID in the Map.

Code:
	  private Map<String, Integer> m_idMap = new HashMap<String, Integer>() ;

	  private void setUpIDs()
	  {
		  m_idMap.put( "R.id.button1", new Integer(R.id.button1) ) ;
		  m_idMap.put( "R.id.button2", new Integer(R.id.button2) ) ;
		  m_idMap.put( "R.id.button3", new Integer(R.id.button3) ) ;
		  . . . etc . . .
		  
	  }

	  private void something()
	  { 
		  String x = "R.id.buttonNb12" ;

		  int id = m_idMap.get(x).intValue() ;
		  Button button = (button)findViewById(id) ;
	   
		  . . . etc . . .
	  }

The code does just enough to illustrate the solutions. Obviously you'll to put additional error checking in.

There's one other solution that would involve using Java Reflection. It's a bit more complicated. I can describe it if you need it, if the other solutions won't work for you.

Mark
 
  • Like
Reactions: JiMMaR and Woulou
Upvote 0
Thanks so much, your answer is very clear. In fact I realize that the key I was looking for is getIdFromString () but I'll have also to use map later in my code so your answer perfectly suit my needs :D.
In fact what seemed strange to me is that the Id is not a string (although it can contain letters) .

Thanks again !
 
Upvote 0
I'm afraid not. You can't do that (well not easily anyway)

Code:
m_idMap.put( "R.id.button[i]", new Integer(R.id.button[i]) ) ;

That takes you back to your original problem of turning an unknown ID into an integer.

You can't do

Code:
 R.id.button[i]

because button isn't an array.

If you're just looking to set up 50 buttons, and you know the IDs in advance, then it might just be easier to do lots of typing, or copy/paste.
(Won't your GUI be a little cramped with 50 buttons on the screen?)

If you want a fully dynamic solution where you can turn the string for any ID into an int, then that's possible using Java reflection. It might be overkill if you just want to save some typing. But if you really need it, I can describe a potential way of doing it. I'll have to go away and write the code first.
 
Upvote 0
Here's some code that will set up a Map with all the ids under R.id.*

Code:
    private Map<String, Integer> m_idMap = new HashMap<String, Integer>() ;
    
    private void createIDMap() {
        R.id ids = new R.id() ;
        
        // Get all the fields declared under R.id 
        Class c = R.id.class ;
        Field fields[] = c.getDeclaredFields() ;
        
        try {
            int i = 0 ;
            while( i<fields.length ) {
                Field field = fields[i] ;
                String idStr = "R.id." + field.getName() ;
                int    idVal = field.getInt(ids) ;
                
                m_idMap.put( idStr, new Integer(idVal) ) ;
                Log.d(TAG, "Adding "+idStr+" with value "+idVal) ;
                i++ ;
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Here's the debug output that I get:

Code:
07-12 00:07:45.087: DEBUG/TempestActivity(1568): Adding R.id.intro with value 2131099657
07-12 00:07:45.092: DEBUG/TempestActivity(1568): Adding R.id.level with value 2131099651
07-12 00:07:45.092: DEBUG/TempestActivity(1568): Adding R.id.life with value 2131099650
07-12 00:07:45.092: DEBUG/TempestActivity(1568): Adding R.id.logo with value 2131099652
07-12 00:07:45.102: DEBUG/TempestActivity(1568): Adding R.id.scores with value 2131099654
07-12 00:07:45.102: DEBUG/TempestActivity(1568): Adding R.id.screenshot with value 2131099653
07-12 00:07:45.112: DEBUG/TempestActivity(1568): Adding R.id.start with value 2131099655
07-12 00:07:45.112: DEBUG/TempestActivity(1568): Adding R.id.status with value 2131099648
07-12 00:07:45.112: DEBUG/TempestActivity(1568): Adding R.id.title with value 2131099656
You can then look up any id given a string, as follows

Code:
  int id = m_idMap.get("R.id.start").intValue() ;
So to loop over 50 buttons, button1 to button50, you could write this:

Code:
  for( int i=0; i<50; i++ ) 
  {
    String idStr = "R.id.button" + (i+1) ;
    int id = m_idMap.get(idStr).intValue() ;
    . . . etc . . .
  }
 
  • Like
Reactions: Woulou
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones